Python List Sorting with sorted() and sort()

In this article, we'll examine multiple ways to sort lists in Python.

Python ships with two built-in methods for sorting lists and other iterable objects. The method chosen for a particular use-case often depends on whether we want to sort a list in-place or return a new version of the sorted list.

Assuming we want to sort a list in place, we can use the list.sort() method as follows:

>>> pets = ['Turtle', 'Cat', 'Fish', 'Dingo']
>>> pets.sort()
>>> pets
['Cat', 'Dingo', 'Fish', 'Turtle']

By default, the list is sorted in ascending order. Notice how the original pets list is changed after the sort method is called on it. If we don't want this to happen, we can use the built-in sorted() function to return a new sorted list while leaving the original list unchanged:

>>> pets = ['Turtle', 'Cat', 'Fish', 'Dingo']
>>> new_pets = sorted(pets)
>>> new_pets
['Cat', 'Dingo', 'Fish', 'Turtle']
>>> pets
['Turtle', 'Cat', 'Fish', 'Dingo']

The reverse argument can be used to sort lists in descending order:

>>> pets = ['Turtle', 'Cat', 'Fish', 'Dingo']
>>> new_pets = sorted(pets, reverse=True)
>>> new_pets
['Turtle', 'Fish', 'Dingo', 'Cat']
>>> pets.sort(reverse=True)
>>> pets
['Turtle', 'Fish', 'Dingo', 'Cat']

However, there are scenarios where we might want to sort a list based on custom criteria that we define. For example, we may want to sort our pets list by the length of each entry. In that case Python offers the key argument, which accepts a user-defined function to specify the sorting criteria:

>>> pets = ['Turtle', 'Cat', 'Fish', 'Dingo']
>>> get_len(x):
...    return len(x)
...
>>> new_pets = sorted(pets, key=get_len)
>>> new_pets
['Cat', 'Fish', 'Dingo', 'Turtle']
>>> pets.sort(key=get_len)
>>> pets
['Cat', 'Fish', 'Dingo', 'Turtle']

Now let's consider a slightly more complex example. Here we have a list of dictionaries that contain data about a group of people, and we want to sort the list based the peoples' ages, in descending order. To do this we will use both the key and reverse keyword arguments, as well as a Python lambda function. That way we can create the sorting function on the fly, instead of defining it beforehand:

>>> data = [ { 'name': 'Billy', 'age': 26, 'country': 'USA' }, { 'name': 'Timmy', 'age': 5, 'country': 'Australia' }, { 'name': 'Sally', 'age': 19, 'country': 'Costa Rica' }, { 'name': 'Tommy', 'age': 67, 'country': 'Serbia' } ]
>>> new_data = sorted(data, key=lambda x: x['age'], reverse=True)
>>> new_data
[{'country': 'Serbia', 'age': 67, 'name': 'Tommy'}, {'country': 'USA', 'age': 26, 'name': 'Billy'}, {'country': 'Costa Rica', 'age': 19, 'name': 'Sally'}, {'country': 'Australia', 'age': 5, 'name': 'Timmy'}]
>>> data.sort(key=lambda x: x['age'], reverse=True)
>>> data
[{'country': 'Serbia', 'age': 67, 'name': 'Tommy'}, {'country': 'USA', 'age': 26, 'name': 'Billy'}, {'country': 'Costa Rica', 'age': 19, 'name': 'Sally'}, {'country': 'Australia', 'age': 5, 'name': 'Timmy'}]

Notice how the dictionaries started in a seemingly random order and then ended up with the oldest people first and youngest people last in the list.

Using the sorting functions and lambdas in this way allows us to easily sort complex data structures, all in one line of code. And the order of the sort can be set to descending order by setting reverse=True.

About the Author

This article was written by Jacob Stopak, a software consultant and developer with a passion for helping others improve their lives through code. Jacob is the creator of Code Card - a convenient tool for developers to look up, copy, and paste common code snippets.

Author image
About Jacob Stopak
San Diego, CA Twitter Website
Jacob Stopak is a software developer and creator of InitialCommit.io - a site dedicated to teaching people how popular programs are coded. Its main project helps people learn Git at the code level.