typestar

Sorting by a key in Python

One pass, one key function, and a stable order you can rely on.

steps = [("traits", 3, 15), ("basics", 1, 39), ("errors", 3, 15)]

print(sorted(steps, key=lambda s: s[0]))
print(sorted(steps, key=lambda s: (-s[1], s[0])))
print(sorted(steps, key=len, reverse=True)[0])

words = ["Bravo", "alpha", "Charlie"]
print(sorted(words), sorted(words, key=str.lower))

How it works

  1. key is called once per item, not per comparison.
  2. A tuple key sorts by several fields at once.
  3. Sorting is stable, so an earlier sort survives a later one.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
294
Tokens
126
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 80 seconds.

Type this snippet

Step 3 of 3 in Sets & mappings, step 58 of 72 in Language basics.

← Previous Next →