# Python Program to Sort a List According to the Second Element in Sublist

«
»

This is a Python Program to sort the list according to the second element in the sublist.

Problem Description

The program takes a list of lists and sorts the list according to the second element in the sublist.

Problem Solution

1. Take in a list containing sublists.
2. Using two for loops, use bubble sort to sort the sublists based on the second value of the sublist.
3. If the second element of the first sublist is greater than the second element of the second sublist, exchange the entire sublist.
4. Print the sorted list.
5. Exit.

Program/Source Code

Here is source code of the Python Program to sort the list according to the second element in the sublist. The program output is also shown below.

```a=[['A',34],['B',21],['C',26]]
for i in range(0,len(a)):
for j in range(0,len(a)-i-1):
if(a[j]>a[j+1]):
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp

print(a)```
Program Explanation

1. User must enter a list containing several sublists.
2. Then bubble sort is implemented to sort the list according to the second element in the sublist.
3. If the second element of the first sublist is greater than the second element of the second sublist, then the entire sublist is switched.
4. This process continues till the entire list has been sorted.
5. The sorted list is then printed.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Runtime Test Cases
```
Case 1:
[['B', 21], ['C', 26], ['A', 34]]```

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions. 