typestar

Generator expressions in Python

Lazy comprehensions that compute one item at a time.

readings = [21.5, 19.8, 23.1, 22.4, 18.9]

total = sum(r for r in readings if r > 20)
hottest = max(r for r in readings)
any_cold = any(r < 19 for r in readings)
all_mild = all(15 < r < 25 for r in readings)

squares = (n * n for n in range(1_000_000))
first = next(squares)
second = next(squares)

count = sum(1 for r in readings if r > 20)

How it works

  1. sum(r for r in readings if r > 20) never builds a list.
  2. any and all short-circuit over the stream.
  3. next pulls single values from an endless expression.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
341
Tokens
103
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 62 seconds.

Type this snippet

Step 4 of 4 in Comprehensions, step 4 of 53 in Pythonic Python.

← Previous Next →