How to Sort a List of Lists in Python [6 Methods]

Are you looking to sort a List of Lists? In this Python tutorial, I will explain “how to sort a list of lists in Python” with six different methods.

While working on one project related to the Python matrix, I had to sort a large amount of data in the nested list (list of lists). Let’s check how to get the expected result with practical examples.

  • Using sort()
  • Using itemgetter with a sorted() method
  • Using sorted() with lambda function
  • Using list comprehension with a sorted() method
  • Using map() with sorted()
  • By creating custom functions

How to Sort a List of Lists in Python using the sort() method

The sort() is a built-in method in Python that sorts the elements of a list in place. By using a sort() along with a lambda function or other callable object, we can easily sort a list of lists according to specific requirements.

The sort() method cannot create a copy of the original list and will modify it directly.

Here is an instance:

Code

list_of_lists = [['New York', 20000000, 800, 30], ['Los Angeles', 15000000, 600, 80], ['Chicago', 9000000, 500, 40]]
# Sort based on the third element of each sublist
list_of_lists.sort(key=lambda x: x[3])
print(list_of_lists)

This code demonstrates sorting an original list of lists in Python using the sort() method.

Output

[['New York', 20000000, 800, 30], ['Chicago', 9000000, 500, 40], ['Los Angeles', 15000000, 600, 80]]

Here’s a snapshot of the code and output captured from Visual Studio

How to sort a list of lists in Python

Sort a List of Lists in Python using itemgetter with the sorted() method

The sorted() function in Python sorts the elements of a list. However, unlike sort(), sorted() returns a new sorted list instead of modifying the original list. We will use itemgetter as a parameter of the sorted() method in Python.

READ:  Python File methods (With Useful Examples)

When sorting a list of lists in Python, one straightforward approach is to use the itemgetter function from the operator module.

Code

from operator import itemgetter
list_of_lists = [['Urban', 10000000, 200, 3], ['Rural', 5000000, 150, 8], ['Suburban', 8000000, 300, 4]]
# Sort based on the first element of each sublist
sorted_list = sorted(list_of_lists, key=itemgetter(1))
print(sorted_list)

In the above example, we’ve sorted a list of lists using the sorted() function along with the itemgetter function from the operator module in Python.

It sorts the list based on the first element of each sublist. The itemgetter(0) function in Python specifies that the sorting key should be the first element of each sublist.

Here is an example to sort a list of lists in Python:

Output

[['Rural', 5000000, 150, 8], ['Suburban', 8000000, 300, 4], ['Urban', 10000000, 200, 3]]

Visual Studio showcases the code snippets and corresponding outputs for each method discussed

Sort Nested List in Python

Python Sort List of Lists using sorted() with lambda function

Lambda functions offer a concise way to define small, anonymous functions in Python.

By combining lambda functions with the sorted() function, we can specify custom sorting criteria based on the elements of the sublists in a list of lists in Python.

Let’s see the example to sort a list of lists in Python:

Code

employee_data = [['John', 35, 'Manager'], ['Emily', 28, 'Engineer'], ['Michael', 40, 'Analyst']]
# Sort based on the age (2nd element) of each employee
sorted_employee_data = sorted(employee_data, key=lambda x: x[1])
print(sorted_employee_data)

The code utilizes the sorted() function and a lambda function to sort a list of lists based on the first element of each sublist in Python.

The lambda function lambda x: x[0] specifies that the sorting key should be the first element of each sublist.

Output

[['Emily', 28, 'Engineer'], ['John', 35, 'Manager'], ['Michael', 40, 'Analyst']]

Here’s a screenshot of the code and output for your reference

Sort a nested Python list

How to order a List of Lists using List Comprehension with the sorted() method

List comprehension in Python provides a compact and elegant way to create lists in Python.

READ:  How to find the size of a Python list

When combined with the sorted() function, list comprehension in Python enables us to sort a list of lists based on specific conditions defined within the comprehension.

Here is an example of using the sorted() function with list comprehension in Python.

Code

customer_data = [[1, 3, 500], [2, 5, 200], [3, 7, 400]]
# Sort based on the purchase amount (third element) of each customer using list comprehension
sorted_customer_data = sorted(customer_data, key=lambda x: max([element for element in x]))
print(sorted_customer_data)

In the above example, we use list comprehension combined with the sorted() function in Python.

sorted(list_of_lists, key=lambda x: max([element for element in x]))

The list comprehension in Python extracts all elements from each sublist x, and max() is applied to find the maximum element.

Output

[[2, 5, 200], [3, 7, 400], [1, 3, 500]]

Look at the code and outputs from Visual Studio, offering a clear perspective on each sorting method.

How to sort a list of lists by a specific index of the inner list

Sorting elements in a list of lists using map() with sorted()

The map() function applies a given Python function to each item of an iterable (such as a list) and returns an iterator of the results.

By utilizing map() along with the sorted() function, we can apply a custom function to each element of the list of lists in Python.

Code


list_of_lists = [[3, 5, 1], [8, 2, 9], [4, 7, 6]]

# Sorting based on minimum element in each sublist
sorted_list = sorted(list_of_lists, key=lambda x: min(map(lambda y: y, x)))
print(sorted_list)

In this code, we’ve used the map() function and the sorted() function to sort a list of lists in Python based on the minimum element in each sublist.

sorted(list_of_lists, key=lambda x: min(map(lambda y: y, x)))

The map() function applies the lambda function lambda y: y to each element of the sublist, and min() is then used to find the minimum element.

READ:  Python list methods with examples

Output:

[[3, 5, 1], [8, 2, 9], [4, 7, 6]]

Screenshots from Visual Studio illustrate the code implementation and resulting output.

Python Sort List of Lists

How to sort a list of lists without using inbuilt functions

We will create a custom function to sort the list of lists in Python, which will take parameters as a list of lists. Then, we will use the bubble sort approach to sort the list of lists without using any built-in method of Python.

Code

def sort_list_of_lists(list_of_lists):
    n = len(list_of_lists)

    for i in range(n):
        for j in range(0, n-i-1):
            if list_of_lists[j] > list_of_lists[j+1]:
                list_of_lists[j], list_of_lists[j+1] = list_of_lists[j+1], list_of_lists[j]

my_list_of_lists = [[3, 5], [1, 2], [4, 6], [2, 3], [5, 1]]
sort_list_of_lists(my_list_of_lists)
print(my_list_of_lists) 

The provided code implements the bubble sort algorithm to sort a list of lists in ascending order based on their first elements in Python.

In each outer loop iteration, the algorithm compares adjacent sublists and swaps them if they are out of order, moving the largest element towards the end of the list. This process repeats until the entire list is sorted in Python.

Output

[[1, 2], [2, 3], [3, 5], [4, 6], [5, 1]]

Here’s the code and output screenshots captured from Visual Studio

How to sort list of lists without using inbuilt functions in python

Note: To learn more about bubble sort in Python, you can refer to the article: Python program for bubble sort

Conclusion

I hope this article has provided a comprehensive overview of various methods to sort a list of lists in Python.

We explored built-in functions like sort() and sorted() along with lambda functions, list comprehension, and the map() function to achieve custom sorting criteria. A custom sorting function using the bubble sort algorithm was also demonstrated for those seeking an alternative approach.

You can efficiently handle sorting tasks in your project using these techniques or methods.

You may also like to read these articles: