← Python lessons

Sorting

This is an extension beyond the core Python concepts. Read Lists and Dictionaries first.

sorted() puts values in order and hands back a new list. It is how a pile of scores becomes a leaderboard.

Sorting a list

scores = [7, 2, 9, 4]
print(sorted(scores))
print(sorted(scores, reverse=True))
print(scores)

reverse=True sorts biggest first. The original list is untouched — sorted() returns a copy.

Sorting in place

.sort() is the other option: it reorders the list itself and returns None.

scores = [7, 2, 9]
scores.sort()
print(scores)

Sorting by a key function

key= tells sorted() how to obtain a comparison value for each item. Pass a function that accepts one item and returns that value.

names = ["Maya", "Bo", "Alexandra"]
print(sorted(names, key=len))
print(sorted(names, key=len, reverse=True))

The first result is ["Bo", "Maya", "Alexandra"], shortest first. The second reverses the length order. Pass len, without parentheses: sorting calls it for each name. Writing len(names) would calculate one number immediately instead of supplying a function.

A dictionary method can also serve as a key function. If scores maps names to numbers, scores.get(name) retrieves one name's score. Passing scores.get lets sorting request a score for each name. Iterating over a dictionary supplies its keys, so the returned list contains names, not scores.

Equal keys keep their order

Python's sorting is stable: items with equal comparison values keep their original relative order. This also holds with reverse=True.

names = ["Zoe", "Amy", "Bo"]
print(sorted(names, key=len))
print(sorted(names, key=len, reverse=True))

The outputs are ["Bo", "Zoe", "Amy"] and ["Zoe", "Amy", "Bo"]. Zoe stays before Amy because both names have three characters and Zoe appeared first. For dictionary keys, the original order is insertion order.

The key function determines the comparison. The examples compare lengths, not alphabetical order. Without a key function, strings compare by their character values; do not assume that this gives dictionary-style ordering for every alphabet.

Predict a ranking

Before running the last example, predict both outputs. Explain why Amy does not move before Zoe. Then change Bo to Bea and predict how having three equal lengths changes the results.

To take only the first few results, read Lists, “Taking part of a list”.


Practise this in the free Python course, where every exercise checks your code instantly.