Sort List of Lists in Python

Python sort list of lists

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.

Output:

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.

Output:

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.

Output:

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 the itemgetter() method.
  • After that, we will pass the get_n object to the sort() method as a key. 
  • When the sort() method is executed using get_n as the key, each inner list is first passed to the get_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.

Output:

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.

Output:

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.

Output:

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.

Output:

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.

Output:

To sort a list of lists using the sorted() function, we can simply pass the input list to the sorted function as follows.

Output:

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. 

Output:

Similar to the itemgetter() method, we can use lambda functions with the sorted() function as follows.

Output:

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.

Output:

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.

Output:

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.

Output:

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. 

Related Posts

  • Remove nan from list in Python
    16 November

    Remove nan From List In Python?

    Table of ContentsWhat is nan in python?How to remove nan from list in python?Remove nan from list using the str() functionRemove nan from list using math.isnan() functionRemove nan from list using numPy.isnan() functionRemove nan from list using pandas.isnull() functionConclusion In python, nan is a special value used to represent missing values. In this article, we […]

  • List intersection in Python
    11 November

    List intersection in python

    Table of ContentsWhat is the list intersection in Python?Ways to find the list intersection in PythonUsing the for loop to achieve list intersection in PythonUsing the set() function to find list intersection in PythonUsing the intersection() function to find list intersection in PythonUsing the filter() and lambda functions to find list intersection in PythonUsing the […]

  • Initialize list with zeros in Python
    25 October

    Four Ways To Initialize List With Zeros In Python

    Table of ContentsWhy Initialize List with Zeros in Python?How Can We Initialize List With Zeros In Python?Initialize List With Zeros Using * Operator In PythonInitialize List With Zeros Using  itertools.repeat() FunctionInitialize List With Zeros Using  Generator Comprehension In PythonInitialize List With Zeros Using  List Comprehension In PythonConclusion Lists in Python are one of the most […]

  • 06 October

    How to find index of all occurrences in list in Python

    Table of ContentsThe easiest method – Using list count() methodThe Basic Method – Using for loopsThe shortest method – Using the enumerate() functionThe fastest method – Using a numpy arrayUsing itertools moduleUsing more-itertools LibraryUsing index() function List is a data type in Python. It is used to store multiple values in one variable. If you […]

  • Convert list to matrix in Python
    21 August

    Convert list to matrix in Python

    Table of ContentsUsing the while loop to convert list to matrix in Python.Use the numpy.array() method to convert list to matrix in Python.Using the numpy.asarray() method to convert list to matrix in Python. Python provides some in-built data types to stock multiple items in a single variable. A List is one among these built-in data […]

  • Sort list alphabetically in Python
    31 May

    Sort list alphabetically in Python

    Table of ContentsUse of the sort() function to sort list alphabetically in Python.Use of the sorted() function sort list alphabetically in Python.Use of the QuickSort algorithm sort list alphabetically in Python. 💡 Outline You can use sort() method of list to sort list alphabetically in Python [crayon-61a23ace4108a914551505/] In this tutorial, we will discuss different ways […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.