Python List sort() — How to Sort a List in Python (Examples)

In Python, a list is a commonly used data type to store values in the same place for easy access. Sorting a list in turn is one of the most common necessities when handling lists of values.

This guide teaches you how to sort a list in Python. After reading this guide, you know how to sort lists of strings, numbers, objects, and much more.

Here is a quick cheat sheet for sorting numbers and strings in Python. If you’re in a hurry, you may find these useful:

numbers = [5, 3, 9, 2, 1, 3, 4]
names = ["Bob", "Charlie", "David", "Alice"]

# Sort in increasing order:
inc_nums = sorted(numbers)

# Sort in decreasing order:
dec_nums = sorted(numbers, reverse=True)

# Sort alphabetically
alpha_names = sorted(names)

# Sort in reversed alphabetic order:
rev_alpha_names = sorted(names, reverse=True)

Let’s jump into sorting!

Sorting a List in Python

There are two ways to sort a list in Python:

  1. Sort a list directly by calling sort() method of a list.
  2. Create a sorted copy of a list by calling sorted() function on a list.

How to Sort a List of Strings in Python

Sorting a list of strings in Python

When sorting a list of strings, there are two main cases you need to learn:

  1. How to sort a list of strings alphabetically.
  2. How to sort a list of strings in reversed alphabetic order.

The best way to learn how to do this is by seeing some examples.

Example 1: Sort a List of Strings Alphabetically

To sort a list of strings alphabetically, you can simply call the built-in sorted() method on the list of strings. This sorts the strings alphabetically by default.

For example:

names = ["Bob", "Charlie", "David", "Alice"]
sorted_names = sorted(names)

print(sorted_names)

Output:

['Alice', 'Bob', 'Charlie', 'David']

Example 2: Sort a List of Strings In Reverse Alphabetic Order

To sort a list of strings in reverse alphabetic order, you need to set the reverse flag to True in the sorted() function call.

For example:

names = ["Bob", "Charlie", "David", "Alice"]
sorted_names = sorted(names, reverse=True)

print(sorted_names)

Output:

['David', 'Charlie', 'Bob', 'Alice']

How to Sort a List of Numbers in Python

Sorting a list of numbers in Python

One of the most common tasks when it comes to sorting a list is sorting a list of numbers.

There are two main cases you need to learn:

  1. How to sort a list of numbers in increasing order.
  2. How to sort a list of numbers in decreasing order.

Example 1: Sort a List of Numbers in Increasing Order

To sort a list of numbers in Python in increasing order, just call the sorted() method on a list of numbers. This method defaults to sorting the numbers in increasing order.

For instance:

numbers = [5, 3, 9, 2, 1, 3, 4]
sorted_numbers = sorted(numbers)

print(sorted_numbers)

Output:

[1, 2, 3, 3, 4, 5, 9]

Example 2: Sort a List of Numbers in Decreasing Order

To sort a list of numbers in decreasing order, call sorted() and set reverse to True.

For example:

numbers = [5, 3, 9, 2, 1, 3, 4]
sorted_numbers = sorted(numbers, reverse=True)

print(sorted_numbers)

Output:

[9, 5, 4, 3, 3, 2, 1]

How to Sort a List of Python Objects

Now you know the very basics of sorting a list in Python.

The next fairly common task to do is to sort a list of objects by specific criteria.

Sorting a list of numbers or strings is “easy” because you are probably looking to sort in increasing order or in alphabetic order.

But when it comes to sorting a list of objects, things get a bit trickier. This is because you need to let Python know what you even mean by sorting objects. You need to choose if you want to sort by some particular property or such.

To sort a list of objects, you need to specify the sort method with a key that specifies the sorting criterion. A common way to specify the key is by using a lambda function.

I think the best way to learn how to sort objects is by seeing an example.

For instance, let’s create a very basic class Fruit with properties weight and name.

class Fruit:
    def __init__(self, weight, name):
        self.weight = weight
        self.name = name

Next, let’s create a list of Fruit objects:

banana = Fruit(1, "Banana")
orange = Fruit(0.25, "Orange")
apple = Fruit(0.5, "Apple")

fruits = [banana, apple, orange]

Let’s sort this list of Fruit objects by their weight. To do this, you need to specify key for the sort method, which acts as a sorting criterion.

fruits.sort(key=lambda fruit: fruit.weight)

If you are unfamiliar with the lambda expression above, make sure to read my complete guide to lambdas in Python.

The above lambda expression is just a function that takes a Fruit object and returns its weight. The sort() method uses this function to sort the objects behind the scenes.

Now let’s print the fruits to see that the sorting indeed took place:

for fruit in fruits:
    print(fruit.name, fruit.weight)

Output:

Orange 0.25
Apple 0.5
Banana 1

Yay! As you can tell, now the fruits are sorted by their weight in increasing order. Make sure to play with the example.

For your convenience, here is the full code for the above example:

class Fruit:
    def __init__(self, weight, name):
        self.weight = weight
        self.name = name
        
banana = Fruit(1, "Banana")
orange = Fruit(0.25, "Orange")
apple = Fruit(0.5, "Apple")

fruits = [banana, apple, orange]

fruits.sort(key=lambda fruit: fruit.weight)

for fruit in fruits:
    print(fruit.name, fruit.weight)

Output:

Orange 0.25
Apple 0.5
Banana 1

How to Sort a List of Dates in Python

Sorting a list of dates in Python

Dealing with dates in Python is common. Sometimes you may have a list of dates you need to sort.

Sorting dates sounds tricky, but it’s actually not.

To sort a list of dates, all you need to do is call the sort() method on the list of date objects.

For example:

import datetime

dates = [datetime.date(2021, 1, 3), datetime.date(2021, 1, 1), datetime.date(2021, 1, 2)]

dates.sort()

print(dates)

Output:

[datetime.date(2021, 1, 1), datetime.date(2021, 1, 2), datetime.date(2021, 1, 3)]

How to Sort a List of Tuples in Python

Sorting a list of tuples that represent 2D coordinates in Python

Tuple is one of the most popular data types in Python. A tuple is an immutable collection of values.

a_tuple = (1, 2, 10)

It’s not rare to have tuples stored in a list. Besides, you might need to sort the list of tuples based on a particular criterion.

The only “tricky” part in sorting tuples is you need to choose the element by which you want to sort the tuples.

So, to sort a list of tuples:

  1. Choose the index of the element based on which you want to sort the list of tuples.
  2. Call sorted() on the list of tuples.

For example, let’s sort a list of tuples that represents 2D coordinate pairs:

# (x, y) coordinate pairs
locations = [
    (0, 2),
    (5, 1),
    (3, 9),
    (1, 6)
]

# Sort locations based on the y coordinate.
sorted_locations = sorted(locations, key=lambda location: location[1])

print(sorted_locations)

Output:

[(5, 1), (0, 2), (1, 6), (3, 9)]

Conclusion

Today you learned how to sort a list in Python in common situations, such as how to sort a list of objects or strings.

To take home, there are two ways to sort a list in Python:

  1. The sorted() function.
  2. The list.sort() method.

Sometimes you need to specify a criterion function based on which the sorting takes place. To do this, specify the key attribute of the sorting method. Usually, this is a lambda function.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading