Python List Comprehensions Cheat Sheet
Python comprehension syntax covering basic list comprehensions, conditional logic, nested comprehensions, dict/set comprehensions, and generator expressions.
1 PageBeginnerMar 22, 2026
Basic List Comprehensions
Building lists from an iterable in a single expression.
python
squares = [x ** 2 for x in range(10)]# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]evens = [x for x in range(20) if x % 2 == 0]pairs = [(x, y) for x in range(3) for y in range(3)]# [(0,0), (0,1), (0,2), (1,0), ...]
Conditional Logic
Ternary expressions inside comprehensions vs. filtering.
python
# ternary expression -> transforms every elementlabels = ["even" if x % 2 == 0 else "odd" for x in range(5)]# trailing if -> filters which elements are includedevens_only = [x for x in range(10) if x % 2 == 0]# combining bothresult = [x if x > 0 else 0 for x in [-2, -1, 0, 1, 2] if x != 0]
Nested Comprehensions
Flattening and transforming nested structures like matrices.
python
matrix = [[1, 2, 3], [4, 5, 6]]flat = [num for row in matrix for num in row]# [1, 2, 3, 4, 5, 6]transposed = [[row[i] for row in matrix] for i in range(3)]# [[1, 4], [2, 5], [3, 6]]
Dict & Set Comprehensions
The same syntax works for dict and set literals.
python
squares_dict = {x: x ** 2 for x in range(5)}# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}unique_lengths = {len(word) for word in ["hi", "bye", "ok"]}# {2, 3}swapped = {v: k for k, v in {"a": 1, "b": 2}.items()}# {1: 'a', 2: 'b'}
Generator Expressions
Lazily-evaluated comprehensions that don't build a full list in memory.
python
gen = (x ** 2 for x in range(10)) # parentheses, not bracketsnext(gen) # 0next(gen) # 1# memory-efficient for large rangestotal = sum(x ** 2 for x in range(1_000_000))
Pro Tip
If a comprehension needs more than two nested `for` clauses or a complex condition, rewrite it as a regular loop — readability drops fast past that point, and a plain loop with clear variable names will be easier to debug.
Was this cheat sheet helpful?
Explore Topics
#PythonListComprehensions#PythonListComprehensionsCheatSheet#Programming#Beginner#BasicListComprehensions#ConditionalLogic#NestedComprehensions#DictSetComprehensions#DataStructures#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance