How to Sort Lists of Lists in Python with Examples

Learn how to sort lists of lists in Python. Explore simple to advanced methods, including, `sorted()`, `map()`, and multi-criteria sorting for complex data.

Why Sort Lists of Lists?

Sorting lists of lists in Python is an essential skill for organizing and analyzing nested data structures, such as student records or multi-attribute datasets. Whether you’re managing student grades, employee records, or complex data, Python offers powerful tools to sort lists of lists efficiently. In this guide, you’ll discover step-by-step methods for sorting lists of lists using Python’s built-in functions like sorted and list.sort(). We’ll also explore advanced techniques such as multi-criteria sorting, transforming data during sorting, and working with custom keys.

What Are Lists of Lists in Python?

A list of lists is a nested data structure where each element of the main list is another list. These sub-lists can represent rows in a table, with each element in the sub-list corresponding to a specific data point. For example, consider a list of students with their grades, ages, and majors:

students_data = [
['Alice', 95, 18, 'Physics'],
['Bob', 82, 19, 'Mathematics'],
['Charlie', 91, 17, 'Chemistry'],
['Diana', 88, 20, 'Biology'],
['Eve', 74, 18, 'History']
]

Each sub-list represents a student record with the following structure:

  • First element: Student’s name
  • Second element: Grade
  • Third element: Age
  • Fourth element: Major

Sorting this data allows us to organize it by criteria like grades, ages, or majors.

Sorting lists of lists using sorted() function with lambda

Python’s built-in sorted() method is an effective way to sort and rank lists, including nested lists. It may be used to efficiently sort data by default based on the first element of each sub-list and has been built to handle a variety of sorting circumstances.

Here’s the basic syntax for it:

sorted(iterable, key=None, reverse=False)
  • iterable: Collection of elements that need to be sorted, such as a list, tuple, or string.
  • key(optional): A function that specifies the sorting criteria. By default, it is set to None.
  • reverse(optional): Represents a Boolean value. It is set to True for descending order and False (default) for ascending order. To better understand how this syntax works in practice, let’s apply the sorted() function to sort a list of lists.

In the following 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_students = sorted(students, key=lambda x: x[1])
# Print the sorted student records in ascending order of grades
print(sorted_students)

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 list is sorted in ascending order by value.

The output of the code will be as follows:

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

The sorted() function does not 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.

Sorting Lists of Lists Using sorted()with List Comprehension

List comprehension with Python’s sorted() function can improve sorting of nested lists by providing an efficient handling of complex sorting tasks . This approach not only allows us to sort nested lists but also provides flexibility to modify or filter elements during the sorting process for clean and maintainable code.

Let’s explore the syntax of using sorted() with list comprehension to efficiently sort and process nested lists:

[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 use sorting with list comprehension to sort the nested list of students records. We’ll sort a nested list of students records by their grades and format the output to make it more readable:

# List of student records with name and grade
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 the formatted sorted list
print(sorted_students)

The output of the code will be 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.

Sorting Lists of Lists using map() and sorted() function

Transforming data while sorting can be challenging. However, Python’s map() function streamlines this process by allowing real-time modifications to elements in nested lists. When combined with sorting, this approach simplifies and enhances data manipulation, making it more efficient and flexible.

Here’s a syntax to transform data during sorting by using Python’s map()function along with the basic sorted() function:

  • function: Function that defines the transformation to be applied for sorting.

Here’s an example demonstrating how to use the map() function in combination with sorted() to apply transformations to elements within nested lists:

# List of student records, each containing a name and grade
students = [['John', 85], ['Anna', 92], ['Rayl', 78], ['Stan', 88]]
# Applying `map()` to increase each student's grade by 5 and sorting the results by 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)

In the code, the map() function adds 5 to each student’s grade, and sorted()sorts the transformed list by grade in ascending order. If we wanted to sord the list in descending order, we can usereverse=Trueto do so.

The output of the code will be as follows:

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

Sorting Lists of Lists Using the list.sort() Method:

In the previous section, we explored how to sort a list of lists using the map() function, where we applied a sorting condition to sort a list. Although the map() function can be very useful for creating new lists or applying functions to elements, it’s not precisely suited for sorting lists. However, the list.sort() method allows us to sort the original list without creating a new one.

The list.sort() method is particularly beneficial for in-place modifications, offering a memory-efficient solution by eliminating the need to create duplicate lists. It directly modifies the original list instead of returning a new sorted list.

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

list.sort(key=None, reverse=False)
  • key(optional): Function that specifies the 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 revisit the example from the previous section, where we had a list of student records, each represented by a sub-list containing a student’s name and grade. This time, we will use the list.sort() method to sort the records directly in place by their grades:

# List of student records: [Name, Grade]
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 the sorted list
print(students)

The output of the code will be the following:

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

In this example:

  • The students list contains sub-lists with a student’s name and grade.
  • The students.sort() method sorts it in place by grade using lambda x: x[1], directly modifying the list before printing the result.

Although Python’s built-in sorting functions like list.sort() and sorted() are highly efficient, they also offer flexibility for custom sorting. Using the key parameter allows for easy definition of custom sorting criteria. This is helpful whenever working with complex data types, such as lists of dictionaries or tuples, or when applying specific rules to determine the order of elements.

Let’s see how we can do this using Python’s key parameter with lambda functions.

Custom Sorting with the key and Lambda Functions

Have you ever wanted to sort lists based on specific attributes, such as organizing students by grades or employees by age?

Python’s key parameter makes this task easy to define precise sorting criteria. By combining the key parameter with lambda functions, we can handle any sorting requirements in a clear and intuitive way.

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 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 individuals by their grades:

# List of student records: [Name, Grade]
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 the formatted and sorted student records
print(formatted_students)

The output of the code will be 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']

By combining the key parameter and lambda functions, we can tailor sorting to fit our specific needs, making it an essential requirement for handling complex data structures.

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:

# List of student records: [Name, Grade, Age]
students = [['John', 85, 20], ['Anna', 92, 22], ['Rayl', 85, 19], ['Stan', 88, 21]]
# Sort by grade (ascending), then by age (ascending) if grades are the same
sorted_students = sorted(students, key=lambda x: (x[1], x[2]))
# Print the sorted list
print(sorted_students)

The output of the code will be as follows:

['Rayl', 85, 19], ['John', 85, 20], ['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 covered how the Python sorted() function excels in many types of sorting jobs, ranging from simple sorting on a single criterion to complicated sorting based on multiple criteria. Such techniques are essential for effectively managing and analyzing complex datasets, such as nested lists.

We also covered multi-criteria sorting for layered data organization and pointed out how combining map() with sorting enables preprocessing, adding flexibility to sorting operations.

By mastering these techniques, developers can better organize and analyze data, which can range from sorting student records to multi-attribute datasets to large-scale information.

Try them with your projects to discover their versatility and flexibility.

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

Author

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