Skip to content
UPEEC

List Comprehensions

A compact way to build lists (and dicts and sets) from other iterables.

Easy
Comments 0
squares = [n * n for n in range(10)]
even = [n for n in range(20) if n % 2 == 0]
volts = {name: adc * 3.3 / 4095 for name, adc in raw.items()}   # dict comprehension

A generator expression uses parentheses and produces values lazily, saving memory:

total = sum(x * x for x in range(1_000_000))

Keep comprehensions short — if one needs several conditions and nested loops, a normal for loop is clearer.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.