Articles

How to Sort Lists in Python (With Examples)

  • 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 are lists in Python?

A list in Python is an inbuilt data structure which contains an ordered collection of items. These items can be of any data type — numbers, strings, or even other lists. Lists are mutable, meaning we can change their contents after creation.

Here is an example of a list:

fruits = ['apple', 'banana', 'cherry']

Python also supports lists of lists, where each element of a list can itself be another list. This is useful for representing tabular or structured data, such as student records or matrix-style datasets.

Here is an example of a list of lists:

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

Here, each inner list holds information about a student. As we learn how to sort lists in Python, handling such nested structures becomes especially important.

In the next section, we’ll learn how to sort lists in Python using the sorted() function with lambda.

Using sorted() function with lambda

Python’s built-in sorted() method is an effective way to sort and rank lists, including nested lists. It can 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 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 the sorted student records in ascending order of grades
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() function can improve sorting of lists in Python by providing an efficient handling of complex sorting tasks. This approach not only allows us to sort lists in Python 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 lists in Python:

[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 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

Transforming data while sorting can be challenging. However, Python’s map() function streamlines this process by allowing real-time modifications to the elements of a list. 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:

sorted(map(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 want to sort the list in descending order, we can use reverse=True to do so.

The output of the code is as follows:

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

Using list.sort() method

In the previous section, we explored how to sort a list in Python 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 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 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']

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 = sorted(students, key=lambda x: (x[1], x[2]))
# Print the sorted list
print(sorted)

The output of the code is 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 tutorial, we learned how to sort lists in Python using methods such as sorted(), map(), and list.sort(), and advanced techniques such as multi-criteria sorting. By mastering these techniques, we can better organize and analyze data, which can range from sorting student records to multi-attribute datasets to large-scale information.

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. Does sorting maintain the original order when elements are equal?

Yes, Python’s sort is stable, meaning equal elements retain their original order.

4. What happens if sublists have different lengths?

Sorting still works as long as the index used in the key exists in every sublist. Otherwise, you’ll get an IndexError.

5. How do I sort in descending order 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