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