Articles

How to Sort Lists of Lists in Python (With Examples)

Sorting lists of lists in Python lets us organize nested data such as student records, product catalogs, or survey results by specific criteria.

In this article, we’ll show you practical methods to sort lists of lists using Python’s built-in functions.

  • Learn about the usefulness and efficiency of computational sorting by implementing different sorting algorithms yourself.
    • With Certificate
    • Intermediate.
      3 hours
  • Learn about the computer science concepts of data structures and algorithms and build implementations of each from scratch in modern Python.
    • Includes 8 Courses
    • With Certificate
    • Intermediate.
      25 hours

What is a list of lists in Python?

A list of lists (also called a nested list) is a list in which each element is a list itself. This structure is ideal for organizing related data in rows and columns, similar to a spreadsheet.

Here’s an example of a list of lists storing student information:

students = [
['Alice', 95, 18],
['Bob', 82, 19],
['Charlie', 91, 17]
]

Each inner list represents one student with their name, grade, and age. Sorting lists of lists allows organizing this data by any element, whether by name, grade, or age.

Now let’s explore how to sort this type of nested data.

Top 6 methods to sort lists of lists in Python

Python offers several built-in methods to sort lists of lists, each suited for different scenarios. Let’s explore six practical methods with examples.

Using sorted() function with lambda

Python’s built-in sorted() function lets you sort a list of lists by any element you choose. It works by examining a specific position in each sub-list (like the second element for grades) and organizing the data accordingly.

Here’s the syntax of the sorted() function:

sorted(iterable, key=None, reverse=False)  
  • iterable: Collection of elements that need to be sorted. In our case, it’s a list of lists.
  • key(optional): Tells Python which element to sort by. Default is the first element.
  • reverse(optional): Represents a Boolean value. It is set to True for descending order and False (default) for ascending order.

Let’s apply the sorted() function to sort a list in Python. In this example, we’ll organize student records by their grades:

# List of student records, each containing a name and grade
students = [['John', 85], ['Anna', 92], ['Rayl', 78], ['Stan', 88]]
# Sort the student records by grades (second element in each sub-list)
sorted = sorted(students, key=lambda x: x[1])
print(sorted)

In this example, the sorted() function sorts student records by grades using a lambda function as the key, which targets the second element of each sub-list. By default, the given list is sorted in ascending order by value.

The output of the code is as follows:

[['Rayl', 78], ['John', 85], ['Stan', 88], ['Anna', 92]]

The sorted() function doesn’t modify the original list. Instead, it returns a new sorted list.

Let’s now explore how to use list comprehension with the sorted() function to achieve a more dynamic and efficient sorting approach.

Using sorted() with list comprehension

List comprehension with the sorted() helps sort and transform the data in one step. This is useful when you want to sort lists of lists and format the output simultaneously, such as converting nested data into readable strings.

The syntax of using sorted() with list comprehension is:

[expression for item in sorted(iterable, key=None, reverse=False)]   

Here:

  • expression: Operation applied to each item in the list.
  • item: The list comprehension takes each element from the sorted iterable and includes it in the final list.

Let’s sort a nested list of students records by their grades and format the output to make it more readable:

students = [['John', 85], ['Anna', 92], ['Rayl', 78], ['Stan', 88]]
# Sort by grades (second element) and format the output
sorted_students = [f"{student[0]}: {student[1]}" for student in sorted(students, key=lambda x: x[1])]
print(sorted_students)

The output of the code is as follows:

['Rayl: 78', 'John: 85', 'Stan: 88', 'Anna: 92']

This example sorts student records by grades in ascending order and formats each record as a string.

Using map() and sorted() functions

Sometimes you need to modify data before sorting it, such as adjusting values or applying calculations. Python’s map() function lets you transform each element in your list of lists, then sort the modified results.

The syntax for this method is:

sorted(map(function)) 
  • map(function, iterable): Applies the transformation to every sub-list
  • sorted(): Then sorts the transformed data

Here’s an example demonstrating each student getting a 5-point grade bonus. We’ll add those bonus points to each grade, then sort the students by their new grades:

students = [['John', 85], ['Anna', 92], ['Rayl', 78], ['Stan', 88]]
# Add 5 bonus points to each grade, then sort by the new grade
sorted_students = sorted(map(lambda x: [x[0], x[1] + 5], students), key=lambda x: x[1])
# Print the sorted student records after transformation
print(sorted_students)

The map() function first adds 5 points to each student’s grade, creating modified sub-lists. Then sorted() organizes these modified records by the new grade values in ascending order.

Note: Add reverse=True to sort in descending order: sorted(map(...), key=lambda x: x[1], reverse=True)

The output of the code is as follows:

[['Rayl', 83], ['John', 90], ['Stan', 93], ['Anna', 97]]

Using list.sort() method

Unlike sorted(), which creates a new list, the list.sort() method modifies your original list directly. This is useful when you want to save memory and don’t need to keep the unsorted version.

Key difference is that sorted() returns a new list, and list.sort() changes the existing list and returns nothing.

Here’s the syntax for list.sort():

list.sort(key=None, reverse=False)  
  • key(optional): Specifies which element in each sub-list to sort by.
  • reverse(optional): A Boolean value when set to True, sorts the list in descending order.

Let’s take the same student records and sort them by grades, but this time the original list will be permanently rearranged:

students = [['John', 85], ['Anna', 92], ['Rayl', 78], ['Stan', 88]]
# Sort the student records in place by grades (second element in each sub-list)
students.sort(key=lambda x: x[1])
print(students)

The output of the code will be the following:

[['Rayl', 78], ['John', 85], ['Stan', 88], ['Anna', 92]]

The students list is now permanently sorted. The lambda x: x[1] tells Python to sort by the grade (second element), and the original list order is replaced with the sorted order.

Custom sorting with key and lambda functions

What if you need to sort by something other than the first element? Python’s key parameter with lambda functions lets you choose exactly which element to sort by, whether it’s the second, third, or any position in your sub-lists.

We can use the key parameter with a lambda function for custom sorting as follows:

sorted(iterable, key=lambda x: x[element_index], reverse=False)    
  • key: The key parameter allows us to define a function applied to each element before sorting. In this case, a lambda function extracts a specific element from each sub-list based on its index. For instance, lambda x: x[element_index] sorts the sub-lists according to the element at the given index.
  • element_index: This index specifies the element in each sub-list used for sorting, allowing dynamic selection of the sorting criterion within nested lists (e.g., name, age, grade).

Let’s sort a list of students by their grades:

students = [['John', 85], ['Anna', 92], ['Rayl', 78], ['Stan', 88]]
# Sort by grade (second element in sub-list) and format as strings
formatted_students = [
f"{name} has a grade of {grade}"
for name, grade in sorted(students, key=lambda x: x[1])
]
print(formatted_students)

The output of the code is as follows:

['Rayl has a grade of 78', 'John has a grade of 85', 'Stan has a grade of 88', 'Anna has a grade of 92']

The key=lambda x: x[1] tells Python to look at the second element (grade) in each sub-list for sorting. You can change x[1] to x[0] for names, x[2] for ages, or any other position.

Advanced sorting with multi-criteria sorting

For more complex sorting scenarios, we should sort by multiple fields. For example, if we wanted to sort student records first by grade and then by name, we could use the key parameter with a tuple to specify multiple sorting criteria. Consider the following example of multi-criteria sorting, where we sort a list of student records first by grade, and if grades are the same, we sort by name:

students = [['John', 85, 20], ['Anna', 92, 22], ['Rayl', 85, 19], ['Stan', 88, 21]]
# Sort by grade (ascending), then by name (ascending) if grades are the same
sorted = sorted(students, key=lambda x: (x[1], x[0]))
print(sorted)

The output of the code is as follows:

[['John', 85, 20], ['Rayl', 85, 19], ['Stan', 88, 21], ['Anna', 92, 22]]

We can also pass reverse=True to sort the results in descending order. Multi-criteria sorting will prioritize the first criterion, then the second if the first one is equal, and so on.

Python’s sorted() function excels in handling everything from basic single-criteria sorting to advanced multi-criteria sorting.

Conclusion

In this article, we walked through what a list of lists is in Python and the top 6 methods to sort lists of lists in Python. We discussed how to use sorted() for creating new sorted lists, list.sort() for in-place sorting, list comprehension for formatting while sorting, map() for transforming data, and multi-criteria sorting using tuples. Each method serves different needs, whether you want to preserve original data, save memory, or sort by multiple elements at once.

Check out Codecademy’s Learn intermediate Python 3 course for more information and advanced techniques on sorting and working with Python lists.

Frequently asked questions

1. Is sort() or sorted() faster?

sort() is usually faster for large datasets since it avoids creating a new list. However, sorted() is more flexible when you want to preserve the original list.

2. What is the difference between sort() and sorted() in Python?

  • sort() is an in-place method that modifies the original list and returns None.
  • sorted() creates and returns a new sorted list, leaving the original unchanged.

3. What does sort() do to a list?

The sort() method rearranges elements in the original list directly, sorting it in place. Unlike sorted(), it modifies the existing list and returns None, making it memory-efficient for large datasets.

4. What is a list of lists called?

A list of lists is called a nested list. It’s a list where each element is itself another list, commonly used to represent tabular data like spreadsheets or matrices.

5. How to sort in descending order in Python using sorted?

Set reverse=True in sorted():

sorted(data, key=lambda x: x[0], reverse=True)
Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team

Learn more on Codecademy

  • Learn about the usefulness and efficiency of computational sorting by implementing different sorting algorithms yourself.
    • With Certificate
    • Intermediate.
      3 hours
  • Learn about the computer science concepts of data structures and algorithms and build implementations of each from scratch in modern Python.
    • Includes 8 Courses
    • With Certificate
    • Intermediate.
      25 hours
  • Learn the basics of recursion and how to implement and analyze important algorithms in Java.
    • Beginner Friendly.
      3 hours