typestar

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

  1. sorted with a key lambda orders books by year.
  2. Another key sorts by lowercased title.
  3. reverse=True flips the order; max with key=len picks.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 6 in Functions, step 35 of 72 in Language basics.

← Previous Next →