Sort a list of lists in Python

By James L.

When dealing with a list of lists, sorting can be done based on the elements of the sublists. 

In this guide, we will explore various techniques to sort a list of lists in Python. We will discuss the following approaches:

  1. Sorting list of lists using sorted() function
  2. Sorting list of lists using sort() method

# Sorting list of lists using sorted() function

In Python, you can use the sorted() function to sort a list of lists based on a specific element within each sublist or based on a custom sorting function.

Understanding sorted() function

The sorted() function in Python is used to sort an iterable object (such as a list, tuple, or string) or a collection of objects in a specified order. It returns a new sorted list from the element of the iterable.

The basic syntax of the sorted() function is as follows:

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

Parameters:

iterable: The iterable (list, tuple, or string) that you want to sort.

key: (Optional) A function that takes an element and returns a key to use for sorting. Useful for custom sorting.

reverse: (Optional) A boolean value. If True, the elements are sorted in descending order. Default is False.

Sorting based on the second element in each sublist

You can provide a custom key function to sort based on the second element of each sublist. 

Here is an example:

list_of_lists = [[1, 20, 300], [100, 2, 30], [10, 200, 3]]

# Sort based on the second element (index 1) in each sublist
sorted_list = sorted(list_of_lists, key=lambda x: x[1])

print(sorted_list)  # Output: [[100, 2, 30], [1, 20, 300], [10, 200, 3]]

In this example, the key=lambda x:x[1] specifies that the sorting should be done based on the second element (index 1) of each sublist.

Descending order sorting based on the second element in each sublist 

If you need to sort a list of lists in descending order based on the second element in each sublist, you can call the sorted() function with the reverse parameter set to True.

Here’s an example:

list_of_lists = [[1, 20, 300], [100, 2, 30], [10, 200, 3]]

# Descending order sorting based on the second element (index 1) in each sublist
sorted_list = sorted(list_of_lists, key=lambda x: x[1], reverse=True)

print(sorted_list)  # Output: [[10, 200, 3], [1, 20, 300], [100, 2, 30]]

Sorting list of lists based on a custom sorting function

You can also define a custom sorting function to decide the sorting criteria.

Here’s an example that sorts a list of lists based on the second element in each sublist:

# Define a custom function to determine the sorting key
def my_func(sublist):
    # Returns the value at index 1 of the sublist
    return sublist[1]


list_of_lists = [[1, 20, 300], [100, 2, 30], [10, 200, 3]]

# Sorting based on the second element (index 1) in each sublist
sorted_list = sorted(list_of_lists, key=my_func)

print(sorted_list)  # Output: [[100, 2, 30], [1, 20, 300], [10, 200, 3]]

Here’s another example that sorts a list of lists based on the sum of their elements:

# Define a custom function to determine the sorting key
def my_func(sublist):
    # Returns the sum of elements in the sublist
    return sum(sublist)


list_of_lists = [[1, 20, 300], [100, 2, 30], [10, 200, 3]]

# Sorting based on the sum of elements in each sublist
sorted_list = sorted(list_of_lists, key=my_func)

print(sorted_list)  # Output: [[100, 2, 30], [10, 200, 3], [1, 20, 300]]

You can customize the my_func() function based on your specific sorting criteria.

Sorting list of lists by the second element using itemgetter()

You can use the itemgetter() function from the operator module to achieve sorting by a second element.

Here’s an example:

from operator import itemgetter

list_of_lists = [[1, 20, 300], [100, 2, 30], [10, 200, 3]]

# Sort based on the second element (index 1) in each sublist
sorted_list = sorted(list_of_lists, key=itemgetter(1))

print(sorted_list)  # Output: [[100, 2, 30], [1, 20, 300], [10, 200, 3]]

Sorting a list of lists by multiple elements 

Sorting a list of lists by multiple elements involves sorting based on multiple criteria or in a specific order for each sublist.

To sort a list of lists by multiple elements, you can pass a tuple of key functions to the key parameter of the sorted() function.

Let’s consider an example where you have a list of people with their names, ages, and salaries. You want to sort the list first by age (ascending) and then by salary(descending). Here is the code: 

# Example list of lists representing people with names, ages, and salaries
people_data = [
    ["Alice", 25, 4000],
    ["Bob", 30, 5000],
    ["Charlie", 25, 8000],
    ["David", 30, 7000]
]

# Sorting the list of people by age (ascending) and then by salary (descending)
sorted_people = sorted(people_data, key=lambda person: (person[1], -person[2]))

print(sorted_people)
# Output: [['Charlie', 25, 8000], ['Alice', 25, 4000], ['David', 30, 7000], ['Bob', 30, 5000]]

In this example, the key parameter of the sorted() function is set to a lambda function that returns a tuple (person[1], -person[2]). This means the sorting is first done by age (index 1) in ascending order and then by salary (index 2) in descending order (the negative sign is used to achieve descending order).

Sorting list of lists by string values

Sorting list of lists based on string values requires special consideration, especially when dealing with case-insensitive sorting. Python provides built-in options to handle these scenarios. 

Here’s an example:

# Example list of lists representing fruits with names and prices
fruits = [["apple", 5], ["Banana", 20], ["Orange", 15], ["grape", 20]]

# Sorting the list of fruits alphabetically by name (case-insensitive)
sorted_fruits = sorted(fruits, key=lambda fruit: (fruit[0].casefold()))

print(sorted_fruits)
# Output: [['apple', 5], ['Banana', 20], ['grape', 20], ['Orange', 15]]

The use of casefold() in the above example is a crucial aspect of sorting the list of fruits alphabetically in a case-insensitive manner. The casefold() method is a string method in Python that returns a version of the string with all Unicode characters converted to their lowercase forms. It is more aggressive in its approach compared to the lower() method, making it suitable for case-insensitive comparisons.

# Sorting list of lists using sort() method

Alternatively, you can also use the sort() method to sort a list of lists in Python.

Understanding sort() method

In Python, the sort() method is used to sort the elements of a list in ascending order by default.

The basic syntax of the sort() method is as follows:

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

list_name: The name of the list you want to sort.
key: (Optional) A function to execute to decide the order. Default is None.
reverse: (Optional) A boolean. If True the list is sorted in descending order. If False (default), the list is sorted in ascending order.

Sorting based on the second element in each sublist

You can use a custom key function with the sort() method to sort sublists based on their second elements, just like you do with the sorted() function.

Here’s an example:

list_of_lists = [[1, 20, 300], [100, 2, 30], [10, 200, 3]]

# Sort based on the second element (index 1) in each sublist
list_of_lists.sort(key=lambda x: x[1])

print(list_of_lists)  # Output: [[100, 2, 30], [1, 20, 300], [10, 200, 3]]

You can replace sorted() function with the sort() method for all the examples we talked about earlier in this guide.

# Differences between the sorted() function and sort() method

The sorted() function and sort() method are both used for sorting elements in a Python list, but they have some key differences:

(1) Return type:

  • sorted(): Returns a new sorted list from the elements of the iterable (list, tuple, or string). The original iterable remains unchanged.
  • sort(): Sorts the elements of the list in-place and returns None. The original list is modified.

(2) Mutability:

  • sorted(): Creates a new sorted list without modifying the original iterable.
  • sort(): Modifies the original list in-place.

(3) Usage:

  • sorted(): It can be used with any iterable (list, tuple, or string), not just lists. It returns a new sorted list regardless of the type of the original iterable.
  • sort(): Applies only to lists. It is a method of the list class and can only be used with lists.

(4) Performance:

  • The sort() method is generally faster than the sorted() function because it modifies the list in-place, avoiding the overhead of creating a new list.

Here’s a table summarizing the key differences:

Feature sorted() sort()
Return Value New sorted list None
Mutability Non-mutating Mutates original list
Usage Any iterable object Lists only
Performance Generally slower Generally faster

Conclusion

In this guide, we discussed how to sort a list of lists using the sorted() function and sort() method.

Here’s a summary of when to use each:

Use sorted():

  • If you want to keep the original list intact.
  • If you need to create a new sorted list from any iterable object.

Use sort():

  • If you want to modify the original list and don’t need to keep the original order.
  • If performance is a major concern.

LivingWithCode → Happy Coding 3000