Playground / Sorting with key= and reverse=

Pick a key and watch Python sort by it

Sorting with key= and reverse=

Interactive lab

Try it: Sorting with key= and reverse=

How sorted() and list.sort() compute key(item) once per item, order the items by those keys with Python's comparison rules, and keep equal keys in their original order — including py4e's sort-a-dict-by-value pattern.

How it works

  1. Decorate: call the key function once on every item (no key means the item itself is compared).
  2. Compare keys with Python's rules: ints by value, strs by code point ('Z' < 'a'), tuples item by item.
  3. Order the items by key; reverse=True puts the largest key first.
  4. Stable: items with equal keys keep their original relative order, also with reverse=True.
  5. sorted() returns a new list; list.sort() rearranges the list in place and returns None; [:N] keeps the first N.

Default run (12 steps): 5 items in their original order. Python will call lambda t: t[1] once per item. … sorted() returned a new list: result = [('fig', 5), ('kiwi', 5), ('pear', 3), ('apple', 3), ('date', 1)].

Simplified: Up to 10 items of one kind (ints, short ASCII words, (word, count) tuples or a small dict) and a fixed menu of key functions. The sorting algorithm itself (Timsort) is not shown — only what it guarantees: the order by key and stability.

Educational simulation

Loading the simulation…