Python

Sort Nested List in Python

Generally, sorting a nested list in Python assists in organizing the data and making it easier to process and analyze. You can use this functionality to sort a list of dictionaries with respect to a particular value, sort a nest of tuples based on a specific element of each tuple, or sort a list of lists. Moreover, sorting nested lists also enhances the user experience when the sorted data is presented to the end users.

This blog will cover the following approaches:

Method 1: Sort Nested List in Python Using “sort()” Method

sort()” is a Python built-in method that sorts elements in a nested list in an ascending order automatically. However, it can be utilized for sorting elements in descending order or based on the specified criteria.

Syntax

To use the “sort()” method in Python, follow the given syntax:

List.sort(reverse=False, key=None)

Here:

  • List” refers to the list that you want to sort.
  • reverse” is an optional parameter that accepts a “False” boolean value for sorting in ascending order, and “True” for descending order.
  • key” is also another optional parameter used for defining a custom sorting function. Moreover, specifying its value as “None” represents the default sorting order.

Example 1: Sorting List in Ascending Order Using “sort()” Method

First of all, define a function named “Sort()” that accepts the unsorted list as an argument. Then:

  • The “List.sort()” method is invoked on the input list.
  • This method accepts a “key” parameter that specifies a lambda function. This parameter tells the sort() method to utilize the lambda function for getting the sorted list of elements.
  • The lambda function specifies a single argument “l” which refers to each tuple in the list and outputs the second element “l[1]”, representing the first index of the tuple.
  • Note that the lambda function assumes the specified element as sortable.
  • Lastly, the function returns the sorted List as the output:
def Sort(List):
    List.sort(key=lambda l: l[1])
    return List

Next, define a nested list, and pass it to the “Sort()” function:

List = [['Zeus', 40], ['Raven', 20], ['Bumblebee', 10], ['Silver Bullet', 50]]
print(Sort(List))

It can be observed that the nested List has been sorted out in ascending order based on the added numeric values:

Method 2: Sort Nested List in Python Using “sorted()” Method

sorted()” Python works pretty similar to the “sort()” method. By default, it also sorts the elements in ascending order. However, the key difference is that the sorted() method can be applied to any iterable, such as dictionaries, or set. Whereas the sort() method does not support this functionality.

Syntax

Check out the following syntax to utilize the “sorted()” method:

sorted(iterable, reverse=False, key=None)

Here, “iterable” represent the input sequence you want to sort (a nested List in this case), and “reverse” and “key” are optional parameters as discussed earlier.

Example

Define a function named “Sort()” that accepts “List1” as an argument, and returns the sorted nested List using the “sorted()” method. As “0” is specified as the first index of the tuple, the sorted() method will return the sorted list based on the first element:

def Sort(List1):
return (sorted(List1, key=lambda i: i[0]))

Then, create a list with the required elements, and pass it to the “Sort()” method:

List1 = [['Zeus', 10], ['Raven', 20], ['Bumblebee', 50], ['Silver Bullet', 30]]
print(Sort(List1))

As you can see, the nested List has been sorted out alphabetically.

Method 3: Sort Nested List in Python Based on Length

The Python “sort()” method can be also utilized to sort the nested list with respect to length. To do so, specify “len” as the value of the “key” parameter as follows:

List.sort(key=len)

Example

Now, create a nested list that comprises further numeric lists. Then, invoke the “sort()” method, and pass “key=len” as arguments. Lastly, call the “print()” function to display the sorted nested Listed on the console:

List1=[[5,10,15,20,25],[2,4,6],[10,15,20,25,30,35]]
List1.sort(key=len)
print(List1)

In this case, the nested List has been sorted out based on the length of the lists (in ascending order):

That was all about sorting nested lists in Python.

Conclusion

For sorting a nested list in Python, use the “sort()” or the “sorted()” method. The sort() follows the “sort(reverse=False, key=None)” syntax. Whereas, to utilize the sorted() method, the “sorted(iterable, reverse=False, key=None)” syntax can be used. Both of these methods can sort a nested list in ascending or descending order or with respect to the index of the tuple. This blog offered different approaches for sorting nesting lists in Python.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor's degree in computer science.