Comprehensions in Python

From the Python cheat sheet ยท Data Structures ยท verified Jul 2026

Comprehensions

Concise syntax for creating lists, dicts, and sets.

python
# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in nums if x % 2 == 0]

# Dict comprehension
{k: v for k, v in pairs}

# Set comprehension
{x.lower() for x in words}
๐Ÿ’ก List comps are faster than equivalent for loops โ€” use them for simple transforms
โšก Generator expressions use () instead of [] โ€” they're lazy and memory-efficient
๐Ÿ“Œ Read nested comps left-to-right: "for row in matrix for n in row"
๐ŸŸข The walrus operator := lets you assign and filter in one expression
comprehensionslist-compgenerators

More Python tasks

Back to the full Python cheat sheet