Lists are one of the essential data types in python. It is just like the array in other programming languages like C++ or Java. And when we want to arrange and store data in some hierarchical form (related data), we use nested lists. A nested list is nothing but a list containing many other lists or lists of lists. In this article, we will study the ways using which we can sort a list of lists in python.
For example, suppose you have some data containing Name of the Vehicle, Type of Vehicle, Average, like this-
Name of the Bike | Model | Mileage of the Bike |
Bajaj Pulsar | Bajaj Pulsar 220 F | 40kmpl |
TVS Apache | tvs apache rtr 160 | 50kmpl |
Yamaha | Yamaha YZF R15 Ver 3.0 | 45 kmpl |
Now, if we want to arrange this data in python. Without any doubt, we are going to use a nested list for that. Like this – [[‘Bajaj Pulsar’,’220 F’,40],[‘TVS Apache‘,’rtr 160’,50],[‘Yamaha’,’YZF R15 Ver 3.0’,45]]
Now, we want to sort this data according to their mileage, or suppose by their names, how do we do this? Let us look at some ways to achieve the same.
Different ways of Sorting the list of lists in python
- Sorting the data by 1st column
- Sorting the data using any other column
- Sorting the list of lists by length
- How to sort the list of lists by the sum of elements
- Sorting the list of lists in descending order
- Creating our own Program to sort the list of lists in Python
1. Sorting the data by 1st column
To sort the data according to the 1st columns in ascending order.
list1=[['Bajaj Pulsar','220 F',40],['Yamaha','YZF R15 Ver 3.0',45],['TVS Apache','rtr 160',50]]
# Using the key parameter of sort method.
# if we use the sort method, the sorting take place in the list itself
list1.sort()
print(list1)
Output-
[['Bajaj Pulsar', '220 F', 40], ['TVS Apache', 'rtr 160', 50], ['Yamaha', 'YZF R15 Ver 3.0', 45]]
When we want to sort the list according to the first columns, we do not need to do anything special. We just need to do everything as usual. Let us see another way of achieving the same.
The above method sorts the data in the original list itself. If we do not wish to make the changes in the original list, we can use the below method.
list1=[['Bajaj Pulsar','220 F',40],['Yamaha','YZF R15 Ver 3.0',45],['TVS Apache','rtr 160',50]]
print(sorted(list1))
# lets see if our original list has changed or not
print(list1)
[['Bajaj Pulsar', '220 F', 40], ['TVS Apache', 'rtr 160', 50], ['Yamaha', 'YZF R15 Ver 3.0', 45]]
Now let us see the naive method using to achieve our goal.
list1=[['Bajaj Pulsar','220 F',40],['Yamaha','YZF R15 Ver 3.0',45],['TVS Apache','rtr 160',50]]
# Iterating through one the list.
#There is no element with which we will compare the last element,
#so we are not including the last element
for i in range(len(list1)-1):
# if the next element is greater then the next element, swap it.
if list1[i][0]>list1[i+1][0]:
list1[i][0],list1[i+1][0]=list1[i+1][0],list1[i][0]
print(list1)
[['Bajaj Pulsar', '220 F', 40], ['TVS Apache', 'YZF R15 Ver 3.0', 45], ['Yamaha', 'rtr 160', 50]]
2. Sorting the data using any other column
To sort the data using any other column, we can use the ‘key’ parameter. We will pass the lambda function as the argument of the key parameter.
Using Column-2:
list1=[[2,100],[6,20],[10,19],[4,54]]
# Sorting the data using second column-
#x[1] indicates columns 2 as index in array starts with 0.
list1.sort(key=lambda x:x[1])
#sorting has took place in the original list
print(list1)
[[10, 19], [6, 20], [4, 54], [2, 100]]
Similarly, if we want to sort the data using the 3rd column, we will pass something like this in the key parameter- lambda x:x[2]
3. Sorting the list of lists by length
If we want to sort the list according to the length of lists inside the list, we can use the key as ‘len’.
list1=[[100,200,300,400,500],[100,200,300],[100,150,200,400]]
# using the key as len
list1.sort(key=len)
print(list1)
[[100, 200, 300], [100, 150, 200, 400], [100, 200, 300, 400, 500]]
4. How to sort the list of lists by the sum of elements
If we want to sort the list according to the sum of elements of the inner list, we can use the key as ‘sum’.
# sum of list inside list - 1050,600,850
list1=[[10,200,300,40,500],[100,200,300],[100,150,200,400]]
# using the key as sum
list1.sort(key=sum)
print(list1)
[[100, 200, 300], [100, 150, 200, 400], [10, 200, 300, 40, 500]]
5. Sorting the list of lists in descending order
Let us now sort the list in descending order. We can use the reverse parameter of the sort method.
list1=[[3,5,111],[16,23,21],[1,2,3,4]]
# for descending order set reverse = True
list1.sort(reverse=True)
print(list1)
[[16, 23, 21], [3, 5, 111], [1, 2, 3, 4]]
We can also sort the list according to the second element and in descending order.
list1=[[3,5,111],[16,23,21],[1,2,3,4],[100,1,31,12]]
# for descending order set reverse = True
# to sort data by 2nd element, use key parameter
list1.sort(key=lambda x:x[1],reverse=True)
print(list1)
[[16, 23, 21], [3, 5, 111], [1, 2, 3, 4], [100, 1, 31, 12]]
6. Creating our own Program to sort the list of lists in Python
Let us create a function which will sort the list according to the given columns number.
def sort_lists(list1,c):
for i in range(len(list1)-1):
# if the next element is greater then the next element, swap it.
# c is the column according to which you want to sort the data
if list1[i][c]>list1[i+1][c]:
list1[i][c],list1[i+1][c]=list1[i+1][c],list1[i][c]
return list1
list1=[['Bajaj Pulsar','220 F',40],['Yamaha','YZF R15 Ver 3.0',50],['TVS Apache','rtr 160',45]]
c=2
sort_lists(list1,c)
[['Bajaj Pulsar', '220 F', 40], ['Yamaha', 'YZF R15 Ver 3.0', 45], ['TVS Apache', 'rtr 160', 50]]
Must Read:
- How to Convert String to Lowercase in
- How to Calculate Square Root
- User Input | Input () Function | Keyboard Input
- Best Book to Learn Python
Conclusion
We have seen a lot of ways using which we can sort the list by the elements of the lists inside the list in python. Also, we can sort the data by the length of the list, the addition of the elements of the list, by the different column in the list. We can also use the reverse parameter to sort the list in descending order.
Try to run the programs on your side and let us know if you have any queries.
Happy Coding!
Good article!
It’s probably worth mentioning that for “Sorting The Data By 1st Column”, if the first elements in each list are identical, then it sorts on the second element on each list, and if the second elements are also identical, it moves on to the third element, etc.
Cheers, Phil
Yes, I’ll edit the post to mention the relative order of records with identical keys.
Hi, in the two occasions in the article where we are manually swapping the elements, it only swaps the element only, not swapping the inner list. I don’t think that is the intended action.
Yes, it doesn’t swap the inner list. Manual swapping can be customized to match our needs. In some cases, we only need to swap the other lists whereas in some inner list needs to be swapped.