Lambdas and sorting in Python
Tiny anonymous functions, mostly as sort keys.
books = [
("Dune", 1965),
("Neuromancer", 1984),
("Foundation", 1951),
]
by_year = sorted(books, key=lambda b: b[1])
by_title = sorted(books, key=lambda b: b[0].lower())
newest_first = sorted(books, key=lambda b: b[1], reverse=True)
double = lambda x: x * 2
titles = [b[0] for b in by_year]
longest = max(titles, key=len)
How it works
sortedwith akeylambda orders books by year.- Another key sorts by lowercased title.
reverse=Trueflips the order;maxwithkey=lenpicks.
Keywords and builtins used here
forlambdalenmaxsorted
The run, in numbers
- Lines
- 13
- Characters to type
- 323
- Tokens
- 114
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 72 seconds.
Step 3 of 6 in Functions, step 35 of 72 in Language basics.