Python Comprehensions — Full Cheat Sheet
Python comprehensions create lists, sets, and dictionaries in a clean, readable, fast way.
1. List Comprehensions
Create new lists using loops, conditions, and transformations.
Basic Syntax
[expression for item in iterable]
Basic Example
numbers = [1, 2, 3, 4, 5] squares = [x * x for x in numbers] print(squares)
With Condition
numbers = [1, 2, 3, 4, 5] evens = [x for x in numbers if x % 2 == 0] print(evens)
If–Else Inside
nums = [1, 2, 3, 4, 5] labels = ["even" if x % 2 == 0 else "odd" for x in nums] print(labels)
Nested Loops
pairs = [(x, y) for x in [1,2] for y in [3,4]] print(pairs)
String Comprehension
text = "hello" chars = [c for c in text] print(chars)
2. Set Comprehensions
Creates sets, removing duplicates automatically.
Basic Set
numbers = [1, 2, 2, 3, 4, 4]
unique_squares = {x * x for x in numbers}
print(unique_squares)With Condition
numbers = [1, 2, 3, 4, 5]
evens = {x for x in numbers if x % 2 == 0}
print(evens)3. Dictionary Comprehensions
Create dictionaries by transforming keys and values.
Basic Example
numbers = [1, 2, 3, 4]
square_dict = {x: x * x for x in numbers}
print(square_dict)With Condition
numbers = [1, 2, 3, 4, 5]
even_dict = {x: x for x in numbers if x % 2 == 0}
print(even_dict)Transform Values
words = ["apple", "banana", "cherry"]
length_map = {word: len(word) for word in words}
print(length_map)4. Nested Comprehensions
Useful for flattening or transforming nested structures.
Flatten List
matrix = [[1,2,3], [4,5,6]] flatten = [num for row in matrix for num in row] print(flatten)
Nested Dictionary
matrix = [[1,2], [3,4]]
mapped = {i: [j*2 for j in row] for i, row in enumerate(matrix)}
print(mapped)Comprehension Summary Table
| Type | Syntax |
|---|---|
| List | [expression for x in iterable] |
| Set | {expression for x in iterable} |
| Dictionary | {key:value for x in iterable} |
| With Condition | [x for x in iterable if condition] |
| Nested | [x for row in matrix for x in row] |