A list comprehension is a compact expression for creating a new list by applying an expression to each element of an iterable, optionally filtering with a condition. The syntax is [expression for item in iterable if condition]. For example, [x**2 for x in range(10) if x % 2 == 0] creates [0, 4, 16, 36, 64] — the squares of even numbers from 0 to 9.
List comprehensions can include multiple for clauses for nested iteration: [(x, y) for x in range(3) for y in range(3)] produces all pairs. They can also include multiple if clauses: [x for x in data if x > 0 if x < 100]. The nesting reads left to right, top to bottom, mirroring the equivalent nested for loops.
List comprehensions are not only more concise than equivalent loops — they are often faster because the iteration and list building happen in optimised C code inside CPython. However, readability should always take priority: if a comprehension becomes too complex (more than two levels of nesting, long expressions), refactoring into a regular loop or helper function is better. For lazy evaluation, use a generator expression instead.
Related terms: Comprehension, List, Generator Expression
Discussed in:
- Chapter 6: Data Structures — List Comprehensions