Code Snippets
/

Python List Comprehension Cheat Sheet

Python List Comprehension Cheat Sheet

List comprehensions are Python's most distinctive feature: they pack filter, map, and flatten into a single expression. This cheat sheet covers the basic map-and-filter form, the nested form for cartesian products and matrix flattening, and the conditional-expression form that branches inside the output. Each pattern shows up many times per Python file in real codebases.

Python
Easy
3 snippets
py-list-comprehensions
py-comprehensions
code-template
cheat-sheet

452 views

11

numbers = [1, 2, 3, 4, 5, 6]

squares = [n * n for n in numbers]
print(squares)  # [1, 4, 9, 16, 25, 36]

even_squares = [n * n for n in numbers if n % 2 == 0]
print(even_squares)  # [4, 16, 36]

lower = [s.lower() for s in ['Alpha', 'BETA', 'Gamma']]
print(lower)  # ['alpha', 'beta', 'gamma']

The base form [expr for x in iterable] is a map. Adding if condition filters which items contribute. Reading order matches normal Python: 'square each number', 'square each number where n is even'. Comprehensions are not just shorter than for plus append, they are also faster because the interpreter avoids the per-iteration LOAD_METHOD overhead. Reach for them whenever the loop body is a single expression and you produce a list.