Table of Contents
Several times we use 2-D lists or lists of lists in our programs to represent a table or matrix. When these tables need to be sorted according to some value, we need to sort the entire list of lists. In this article, we will discuss different approaches to sort a list of lists in python.
Sort List of Lists Using the sort() Method in Python
Normally, the sort()
method is used to sort a 1-D list. When invoked on a list, it sorts the elements of the list in increasing order as follows.
1 2 3 4 5 6 |
myList = [1, 2, 5, 3, 77, 12, 104, 34] print("The input list is:",myList) myList.sort() print("The sorted list is:",myList) |
Output:
1 2 3 4 |
The input list is: [1, 2, 5, 3, 77, 12, 104, 34] The sorted list is: [1, 2, 3, 5, 12, 34, 77, 104] |
If we have a list of lists and we invoke the sort()
method on the list, it rearranges the position of inner lists according to their first element. i.e. The inner list that has the smallest first element comes in the first position and the inner list that has the greatest first element goes to the last.Â
If two inner lists have the same first element, their position is decided based on the second element and the inner list with smaller second elements comes first. You can observe this scenario in the following example.
1 2 3 4 5 6 |
myList = [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] print("The input list is:", myList) myList.sort() print("The sorted list is:", myList) |
Output:
1 2 3 4 |
The input list is: [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] The sorted list is: [[5, 3, 77], [12, 104, 34], [504, 1, 2, 12]] |
However, we can also decide the criteria on which the inner lists will be sorted. We can decide the index of the element in the inner lists that will be used to compare the inner lists. For this, we can use the itemgetter()
method or lambda
functions. Let us discuss them one by one.
Using the itemgetter() method
The itemgetter()
method is defined in the operator module. It takes a number ‘n
’ as its input argument and returns a callable object (For simplicity, you can call it a function). We can use the callable object to get the element at index ‘n
’ from any list.Â
Let us understand this using the following example.
1 2 3 4 5 6 7 8 |
from operator import itemgetter get_n = itemgetter(3) myList = [1, 2, 5, 3, 77, 12, 104, 34] print("The input list is:", myList) print("The element at index 3 is:", get_n(myList)) |
Output:
1 2 3 4 |
The input list is: [1, 2, 5, 3, 77, 12, 104, 34] The element at index 3 is: 3 |
Here, we have first created a callable object and assigned it to get_n
by using the itemgetter()
method. You can observe that we have passed the number 3 to the itemgetter()
method. Due to this, whenever we will pass a list to the get_n()
object as an input argument, it will return the element at index 3 as you can see in the output.
To sort a list of lists using the itemgetter()
method, we will follow the following approach.
Suppose that we have to rearrange the inner lists based on the element at the index n.
- First, we will create an itemgetter object
get_n
using theitemgetter()
method. - After that, we will pass the
get_n
object to thesort()
method as a key. - When the
sort()
method is executed usingget_n
as the key, each inner list is first passed to theget_n
object as an input argument which then returns the element at the index n. This element is used to compare the inner lists to sort the list of lists in python.
For instance, we can sort a list of lists using the element at index 2 of the inner lists as key as shown below.
1 2 3 4 5 6 7 8 9 |
from operator import itemgetter get_n = itemgetter(2) myList = [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] print("The input list is:", myList) myList.sort(key=get_n) print("The sorted list is:", myList) |
Output:
1 2 3 4 |
The input list is: [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] The sorted list is: [[504, 1, 2, 12], [12, 104, 34], [5, 3, 77]] |
Always keep in mind that there should be at least n+1
elements in all the inner lists. Otherwise, an IndexError
exception will occur if the get_n
method tries to retrieve an element at index n of an inner list with less than n+1
elements.
You can observe this in the following example.
1 2 3 4 5 6 7 8 9 |
from operator import itemgetter get_n = itemgetter(4) myList = [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] print("The input list is:", myList) myList.sort(key=get_n) print("The sorted list is:", myList) |
Output:
1 2 3 4 5 6 7 |
The input list is: [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 6, in <module> myList.sort(key=get_n) IndexError: list index out of range |
Using Lambda Functions
Using the itemgetter()
method, we can only use the elements of the inner lists as keys for comparing the inner lists. Suppose that we want to use the absolute value of the elements instead of the actual elements as the key for comparing the inner lists. In such a case, we can use the lambda
functions.
Lambda functions are single-line functions that can accept any number of arguments but can have only one statement. The syntax of a lambda function is as follows.
lambda [arguments]: expression
Here,
lambda
is a keyword.arguments
are the input arguments that we want to pass to the lambda function. We have written arguments in a list to show that there can be more than one argument.expression
is the expression consisting of input arguments. It may also be a function call.
To sort a list of lists using the lambda function, we will create a lambda function and pass it as the key to the sort()
method.Â
To sort a list of lists using the element at index n of the inner list,
- We will pass the inner lists as the input argument to the lambda function.
- We will use the element at index n of the inner list as the expression in the lambda function.
You can observe the entire process in the following example.
1 2 3 4 5 6 7 |
myList = [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] print("The input list is:", myList) myList.sort(key=lambda inner_list:inner_list[2]) print("The sorted list is:", myList) |
Output:
1 2 3 4 |
The input list is: [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] The sorted list is: [[504, 1, 2, 12], [12, 104, 34], [5, 3, 77]] |
Here, we have sorted a list of lists using the lambda function by comparing the element at index 2 of the inner lists.
If you want to use the absolute value of the elements of the inner lists for comparing them, you can call the abs()
function with the element of the inner list as an input argument in the lambda function as follows.
1 2 3 4 5 6 |
myList = [[504, -1, 2, 12], [5, 3, 77], [12, -104, 34]] print("The input list is:", myList) myList.sort(key=lambda inner_list: abs(inner_list[1])) print("The sorted list is:", myList) |
Output:
1 2 3 4 |
The input list is: [[504, -1, 2, 12], [5, 3, 77], [12, -104, 34]] The sorted list is: [[504, -1, 2, 12], [5, 3, 77], [12, -104, 34]] |
Further reading:
Sort List of Lists Using the sorted() Function in Python
While using the sort()
method, the original list gets modified. To avoid this, you can use the sorted()
function. The sorted()
function takes a list as input and returns a new list with elements of the input list in sorted order as follows.
1 2 3 4 5 6 |
myList = [1, 2, 5, 3, 77, 12, 104, 34] print("The input list is:", myList) newList = sorted(myList) print("The sorted list is:", newList) |
Output:
1 2 3 4 |
The input list is: [1, 2, 5, 3, 77, 12, 104, 34] The sorted list is: [1, 2, 3, 5, 12, 34, 77, 104] |
To sort a list of lists using the sorted()
function, we can simply pass the input list to the sorted function as follows.
1 2 3 4 5 6 |
myList = [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] print("The input list is:", myList) newList=sorted(myList) print("The sorted list is:", newList) |
Output:
1 2 3 4 |
The input list is: [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] The sorted list is: [[5, 3, 77], [12, 104, 34], [504, 1, 2, 12]] |
Here, you can see that the inner lists have been arranged according to their first argument as it was done in the case of the sort()
method.
We can also use the itemgetter()
method and the lambda function
to sort the list of lists using a specified key as we did with the sort()
method.Â
We can use the itemgetter()
method with the sorted()
function to sort a list of lists as shown below. Here, the mechanism of the itemgetter()
method is similar to that we discussed while using it with the sort()
method.Â
1 2 3 4 5 6 7 8 9 |
from operator import itemgetter get_n = itemgetter(2) myList = [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] print("The input list is:", myList) newList = sorted(myList, key=get_n) print("The sorted list is:", newList) |
Output:
1 2 3 4 |
The input list is: [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] The sorted list is: [[504, 1, 2, 12], [12, 104, 34], [5, 3, 77]] |
Similar to the itemgetter()
method, we can use lambda functions with the sorted()
function as follows.
1 2 3 4 5 6 |
myList = [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] print("The input list is:", myList) newList = sorted(myList, key=lambda inner_list: inner_list[1]) print("The sorted list is:", myList) |
Output:
1 2 3 4 |
The input list is: [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] The sorted list is: [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] |
Sort lists of lists on the basis of the length of the inner lists
The len()
function is used to calculate the length of a list. It accepts a list as an input argument and returns the length of the list as follows.
1 2 3 4 5 |
myList = [504, 1, 2, 12, 5, 3, 77, 12, 104, 34] print("The input list is:", myList) print("The length of the list is:", len(myList)) |
Output:
1 2 3 4 |
The input list is: [504, 1, 2, 12, 5, 3, 77, 12, 104, 34] The length of the list is: 10 |
To sort a list of lists according to the length of inner lists, we will use the length of the inner lists as the key for sorting. For this, we will use the len()
function as the key with the sort()
method as follows.
1 2 3 4 5 6 |
myList = [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] print("The input list is:", myList) myList.sort(key=len) print("The sorted list is:", myList) |
Output:
1 2 3 4 |
The input list is: [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] The sorted list is: [[5, 3, 77], [12, 104, 34], [504, 1, 2, 12]] |
Alternatively, we can use the sorted()
function and the len()
function to sort the list of lists according to their length while keeping the original list unmodified as follows.
1 2 3 4 5 6 |
myList = [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] print("The input list is:", myList) newList = sorted(myList, key=len) print("The sorted list is:", newList) |
Output:
1 2 3 4 |
The input list is: [[504, 1, 2, 12], [5, 3, 77], [12, 104, 34]] The sorted list is: [[5, 3, 77], [12, 104, 34], [504, 1, 2, 12]] |
Conclusion
In this article, we have discussed different ways to sort a list of lists in python. You can use any approach for your work according to your needs. If you don’t want to modify the original list, you can use the sorted()
function. Otherwise, you can use the sort()
method to sort the list of lists in python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning.