0
Sort with a Key1 / 4

CRASH COURSE

Sort with a Key

sorted returns a new list. list.sort changes a list in place and returns None. Confusing these behaviors is a common source of bugs.

  • A key function supplies the value used for comparison. key=len sorts strings by length rather than alphabetical order.
  • reverse=True sorts descending. Python sorting is stable: equal keys preserve their original relative order.
words = ["pear", "fig", "banana"]
print(sorted(words, key=len))