Sorting

sorted(xs) returns a new sorted list and works on anything you can loop over. xs.sort() sorts the list in place and returns None. A classic bug is xs = xs.sort(), which leaves you with None.

Both take the same options:

  • key= is a function that turns each item into the value to compare, like key=len or key=str.lower.
  • reverse=True sorts from high to low.

Python's sort is stable: items that compare equal keep their original order. Below, "pear" stays before "kiwi" because both have 4 letters.

To sort by several things, return a tuple from the key. Tuples compare item by item. Negate a number to flip just that part, so (-age, name) means oldest first, then by name A to Z.

Sorting costs O(n log n). Run it, then sort people by name first and age second.