Skip to content
Justice Tech School

Sorting with key and Sorted

Pass key= to sort by any rule and reverse=True to flip. operator.itemgetter is a fast key for tuples and dicts.

Example
people = [("Zed", 20), ("Ada", 30)]
print(sorted(people, key=lambda p: p[1], reverse=True))
print(sorted(["b", "A", "c"], key=str.lower))

Result

[('Ada', 30), ('Zed', 20)]
['A', 'b', 'c']

Exercise

Sort rule argument.

sorted(x, =len)

Quiz Test

What does key= take?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.