Sorting

Sorting shows up in a lot of problems, even when it isn’t the main point. You might sort intervals before merging them. You might sort a dictionary by value to find the top result. Python gives you two ways to sort. Both take a key= argument. You can use it for almost every sort you’ll need.

sort() vs sorted(): in place or a new list

O(n log n)

sorted() takes any iterable and returns a new sorted list. It doesn’t change the original:

numbers = [4, 2, 7, 1, 9, 3]

new_list = sorted(numbers)
print(numbers)
print(new_list)
main.py

list.sort() is a method on lists that sorts in place and returns None:

numbers = [4, 2, 7, 1, 9, 3]
result = numbers.sort()
print(numbers)
print(result)
main.py

Note

The big gotcha: sort() returns None. If you write numbers = numbers.sort(), you throw away your list. numbers is now None, not a sorted list:

numbers = [4, 2, 7, 1, 9, 3]
numbers = numbers.sort()
print(numbers)
main.py

Call numbers.sort() on its own line if you want to sort the list you already have. Use sorted() instead if you want a new list and want to keep the original too.

Sorting with key=

O(n log n)

key= takes a function. Python calls it on every element and sorts by what it returns. The elements themselves don’t change. Only their order does. Here’s how to sort by string length:

words = ["banana", "kiwi", "watermelon", "fig"]
print(sorted(words, key=len))
main.py

By default, uppercase letters sort before lowercase ones. Use str.lower to ignore case:

names = ["bob", "Alice", "charlie", "Dave"]
print(sorted(names))
print(sorted(names, key=str.lower))
main.py

Here’s how to sort numbers by absolute value:

nums = [3, -7, 1, -2, 8, -1]
print(sorted(nums, key=abs))
main.py

Note

To sort largest first, add reverse=True to any of these calls. You don’t need to change the key function. A key that makes the value negative works too, but only for numbers. It’s also easy to get wrong. We recommend reverse=True.

How do I sort a list of tuples by the second element?

Most people write this with a lambda that pulls out the field they care about:

scores = [("alice", 91), ("bob", 78), ("carol", 85)]
print(sorted(scores, key=lambda pair: pair[1]))
main.py

operator.itemgetter does the same job without a lambda. It’s easier to read once you’re used to it:

from operator import itemgetter

scores = [("alice", 91), ("bob", 78), ("carol", 85)]
print(sorted(scores, key=itemgetter(1)))
main.py

Both give the same result. Use whichever one you remember faster under pressure. Use the lambda if you’re not sure you’ll remember the import.

How do I sort a dictionary by its values?

Dicts don’t have a .sort() method. Instead, sort the dict’s .items(). That gives you a list of (key, value) tuples. Then you can sort them by the value:

scores = {"alice": 91, "bob": 78, "carol": 85}
ranked = sorted(scores.items(), key=lambda item: item[1])
print(ranked)
print(dict(ranked))
main.py

Note

You can pass the sorted list of tuples back into dict(). Since Python 3.7, dicts remember the order you add keys in. The new dict keeps the order you just sorted into. It’s a quick way to get a dict sorted by value.

Sorting objects by attribute

This works the same way as tuples. The only difference is that you pull out an attribute instead of an index:

class Player:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def __repr__(self):
        return f"Player({self.name!r}, {self.score})"


players = [Player("alice", 91), Player("bob", 78), Player("carol", 85)]
print(sorted(players, key=lambda p: p.score))
main.py

operator.attrgetter is the attribute version of itemgetter. It’s especially handy when you sort by more than one attribute at a time:

from operator import attrgetter


class Player:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def __repr__(self):
        return f"Player({self.name!r}, {self.score})"


players = [Player("alice", 91), Player("bob", 78), Player("carol", 85)]
print(sorted(players, key=attrgetter("score")))
main.py

Sorting by multiple keys

If key= returns a tuple, Python compares the tuples one element at a time. This example sorts by age first. People with the same age are sorted by name:

people = [("carol", 25), ("dave", 30), ("bob", 25), ("alice", 30)]
print(sorted(people, key=lambda p: (p[1], p[0])))
main.py

Note

Another way to do it: Python’s sort is stable. That means equal elements stay in the same order they started in. So you can sort by the less important key first. Then sort by the more important key. You get the same result as a tuple key:

people = [("carol", 25), ("dave", 30), ("bob", 25), ("alice", 30)]

by_name = sorted(people, key=lambda p: p[0])
by_age = sorted(by_name, key=lambda p: p[1])
print(by_age)
main.py

A tuple key is usually simpler. Sorting twice is useful when the keys get complicated. It also helps when you need to sort one key ascending and another descending.

Why do I get TypeError when sorting?

Python 3 compares elements with < while it sorts. It can’t compare an int to a str. You get an error if you mix them:

values = [3, "two", 1]
try:
    print(sorted(values))
except TypeError as e:
    print(f"TypeError: {e}")
main.py

Note

Python 2 let you pass a cmp= function that could compare any two values. Python 3 removed cmp= completely. It uses key= instead. Turn the values into one type with a key function like key=str if your data really does mix types.

Where sorting shows up in interviews

Sorting is rarely the whole problem. It’s often the first step, though. The biggest pattern to know is intervals. Almost every interval problem starts by sorting the intervals, usually by start time.

  • In Intervals, we explain why sorting first helps. Once the intervals are in order, you only need to go through them once.
  • In Merge Intervals, you sort by start time. Then you go through the list once and merge any interval that overlaps the one before it.
  • In Meeting Rooms II, you sort the start times and end times separately. That lets you count how many rooms are in use at once.
  • In Non-overlapping Intervals, you sort by end time instead of start time. A lot of people miss that detail the first time they see it.