Paul's Python CoursePPC

Sorting with key=

Not met yet

sorted(items, key=f) calls f on every item and sorts by what comes back, but hands back the items themselves. key=len sorts by length; key=lambda stall: stall[1] by the second part. Pass the function, don't call it: key=len, not key=len(). reverse=True puts the biggest first, and .sort(), max and min take key= as well.

Try it

main.py

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks sorted(items, key=f) hands back the key values rather than the original items.
  • Writes key=len() or key=f() and thinks the key function must be called before it is passed.

Where it comes up