Skip to content

Python List sort(): An In-Depth Guide to Sorting Lists

Python List Sort Sorting Lists in Python Key Lambda Cover Image

In this tutorial, you’ll learn how to use Python to sort a list using the sort() method. Being able to work with lists is an essential skill in Python, given their prevalence. Because lists are ordered and mutable data structures, we can modify their order. The list.sort() method allows you to do exactly this! The method is a valuable method that allows you to sort in many custom ways.

By the end of this tutorial, you’ll have learned:

  • How to use the Python sort method to sort a list
  • How to sort in ascending, descending and custom orders
  • How to sort lists of lists, lists of tuples, and lists of dictionaries

Let’s get started!

Python List sort() Method Syntax

The Python `sort() method sorts the elements of a list in a given order, including ascending or descending orders. The method works in place, meaning that the changed list does not need to be reassigned in order to modify the list.

Let’s take a look at the parameters of the function:

# The Parameters of the .sort Method
list.sort(
	key=None,
	reverse=False)

As you can see in the block above, the method has two parameters:

  1. key= specifies the function of one argument that is used to compare against another list element. By default, the parameter is set to None, which means that the list items are sorted directly, without calculating a separate key value.
  2. reverse= specifies the order in which to sort values. By default, the argument is set to False, meaning that the data are sorted in ascending order.

The .sort() method doesn’t return anything, though it does modify the original list directly. If this is behaviour that you’re hoping for or expecting, then the sorted() function is a better fit for this.

In the following sections, you’ll learn how to use the .sort() method to sort values in a list. First, you’ll learn how to sort a list in ascending order.

Sort a Python List in Ascending Order

In this section, you’ll learn how to sort a list in ascending order using the .sort() method. By default, the method will use the reverse=False argument, meaning that items will be sorted in ascending order by default. Because of this, we can skip entering this parameter.

Let’s take a look at an example of how to sort a list in ascending order in Python:

# Sorting a List in Ascending Order
name = ['d', 'a', 't', 'a', 'g', 'y']
name.sort()
print(name)

# Returns:
# ['a', 'a', 'd', 'g', 't', 'y']

We can see that the values are sorted in ascending order. One important thing to note is that the values are compared directly.

This means that items in the list are treated as they are – capital letters will follow a different sort order than lowercase letters. In the custom sort order section, you’ll learn how to overwrite this behaviour.

In the following section, you’ll learn how to sort a list in descending order using the Python .sort() method.

Sort a Python List in Descending Order

Similar to sorting a list in ascending order, we can sort a Python list in descending order using the .sort() method. While the function will, by default, sort a list in ascending order, we can modify this behaviour by changing the reverse= parameter to True.

Let’s see how we can sort a list in reverse order using the .sort() method:

# Sorting a List in Descending Order
name = ['d', 'a', 't', 'a', 'g', 'y']
name.sort()
print(name)

# Returns:
# ['y', 't', 'g', 'd', 'a', 'a']

Similar to the note in the previous section, capital letters will be treated differently. However, in the following section, you’ll learn how to sort a Python list in a custom order.

Sort a Python List in Custom Order with Key

The Python .sort() method allows you to further refine the order in which items are sorted by making use of the key=parameter. Let’s take look at an example that I’ve alluded to in the two previous sections: how capital letters are treated.

Let’s change a letter to a capital letter in the list and see how this changes the sort order:

# Seeing Sort Order with Capital Letters
name = ['D', 'a', 't', 'a', 'g', 'y']
name.sort()
print(name)

# Returns:
# ['D', 'a', 'a', 'g', 't', 'y']

We can see that the capital 'D' is sorted before the lowercase letters. This is because the values are sorted by their ASCII values, where the capital letters have lower values than their lowercase versions.

This is where the key= parameter comes into play! We can pass in a key that accepts a function to change the sort order. If we want to compare all the letters by their case, we can, for example, pass in the str.lower callable.

Let’s see what this looks like:

# Sorting a List of Letters With Mixed Capitalization
name = ['D', 'a', 't', 'a', 'g', 'y']
name.sort(key=str.lower)
print(name)

# Returns:
# ['a', 'a', 'D', 'g', 't', 'y']

We can take this even further by passing in a custom function! Say we wanted to sort a list of strings by their last letter, we can first create a function that returns the last letter of each item passed into it.

Let’s take a look at an example of how we can do this:

# Sorting a List with a Custom Function
words = ['apple', 'banana', 'grapefruit', 'plum']

def get_last(word):
    return word[-1]

words.sort(key=get_last)
print(words)

# Returns:
# ['banana', 'apple', 'plum', 'grapefruit']

In the next section, you’ll learn how to use an anonymous lambda function to define a custom sort order.

Sort a Python List in a Custom Order with Lambda

In many cases, you will not use the custom sort function again. Because of this, it makes sense to use an anonymous lambda function. Let’s see how we can recreate the sorting method above using a lambda function:

# Sorting a List with a Lambda Function
words = ['apple', 'banana', 'grapefruit', 'plum']

words.sort(key=lambda x: x[-1])
print(words)

# Returns:
# ['banana', 'apple', 'plum', 'grapefruit']

We can see that this has a number of key benefits:

  1. It reduces the amount of code we need to write
  2. We make it more clear what our sort function does by not needing to move to another line of code

In the following sections, you’ll learn how to sort different common list structures, such as lists of lists, lists of tuples, and lists of dictionaries.

Sort a Python List of Lists

In this section, you’ll learn how to sort a list of lists in Python using the .sort() method. In this example, we’ll sort a list of lists by their length, in ascending order (from shortest to longest).

Again, we can do this by using the key= parameter and passing in the len callable. This will sort by the returned value of the len() function, in ascending order:

# Sorting a List of Lists by Their Length
lists = [[1,2,3], [4, 5], [6], [7,8,9, 10]]
lists.sort(key=len)

print(lists)

# Returns:
# [[6], [4, 5], [1, 2, 3], [7, 8, 9, 10]]

We can see here that each list is sorted by its length, so that shorter sublists are sorted before longer one.

Sort a Python List of Tuples

Sorting a Python list of tuples in the same way that you would sort a list of lists. Because of this, let’s take a look at an example that shows how to sort using a different key.

For example, imagine we have a tuple that contains (country, number_of_medals), we can sort our list of countries in the order of most to least medals. Let’s see how we can do this:

# Sorting a List of Tuples
countries = [('Spain', 10), ('Portugal', 3), ('Italy', 5), ('Germany', 23), ('France', 12)]
countries.sort(key=lambda x: x[1], reverse=True)

print(countries)

# Returns:
# [('Germany', 23), ('France', 12), ('Spain', 10), ('Italy', 5), ('Portugal', 3)]

We can see that we sorted the tuples by their number of medals in descending order. We did this by using a lambda function and accessing the first index item.

Sort a Python List of Dictionaries

In this final section, we’ll explore how to sort a list of dictionaries. Because dictionaries are made up of key:valuepairs, the items can’t be accessed by their index. Imagine we have the following dictionary:

# A List of Dictionaries Containing People
people = [
    {'Name': 'Nik', 'Age': '33', 'City': 'London'}, 
    {'Name': 'Kate', 'Age': '32', 'City': 'Paris'}, 
    {'Name': 'Mike', 'Age': '23', 'City': 'Berlin'}]

Say we wanted to sort the list of people by their age, in ascending order. In order to do this, we need to access the value for the 'Age' key. We can do this by using the .get() method.

We can pass the .get() method into a lambda function and access the 'Age' key:

# Sorting a List of Dictionaries by a Value
people = [
    {'Name': 'Nik', 'Age': '33', 'City': 'London'}, 
    {'Name': 'Kate', 'Age': '32', 'City': 'Paris'}, 
    {'Name': 'Mike', 'Age': '23', 'City': 'Berlin'}]

people.sort(key=lambda x: x.get('Name'))

print(people)

# Returns:
# [{'Name': 'Kate', 'Age': '32', 'City': 'Paris'}, 
# {'Name': 'Mike', 'Age': '23', 'City': 'Berlin'}, 
# {'Name': 'Nik', 'Age': '33', 'City': 'London'}]

Conclusion

In this post, you learned how to use Python to sort lists using the .sort() method. You learned how the syntax of the Python sort method works. Then, you learned how to use the method to sort Python list items in ascending, descending and custom orders. Then, you learned how to sort lists of lists, lists of tuples, and lists of dictionaries.

Additional Resources

To learn more about related topics, check out the tutorials below:

Leave a Reply

Your email address will not be published.