Syntax
[expression for item in iterable if condition]Examples
Basic Comprehension
Transforming every item in a list.
numbers = [1, 2, 3, 4, 5]
squares = [n ** 2 for n in numbers]
print(squares) # [1, 4, 9, 16, 25]
# Equivalent traditional loop
squares2 = []
for n in numbers:
squares2.append(n ** 2)Comprehension with a Condition
Filtering items using an if clause.
numbers = range(1, 21)
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, ..., 20]
words = ["hi", "hello", "hey", "greetings"]
long_words = [w for w in words if len(w) > 3]
print(long_words) # ['hello', 'greetings']Comprehension with if/else
Using a conditional expression inside the comprehension to transform, not just filter.
numbers = [1, 2, 3, 4, 5, 6]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels) # ['odd', 'even', 'odd', 'even', 'odd', 'even']Nested List Comprehension
Flattening a 2D list or building a grid using nested loops within a comprehension.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
grid = [[r * c for c in range(3)] for r in range(3)]
print(grid) # [[0, 0, 0], [0, 1, 2], [0, 2, 4]]Best practices
- Use list comprehensions for simple transformations and filters - switch back to a regular loop once logic gets complex or hard to read on one line
- Avoid nesting more than two levels deep in a single comprehension - it quickly becomes unreadable
- Use a generator expression (parentheses instead of brackets) when you only need to iterate once and want to save memory
- Remember a comprehension always builds the entire list in memory immediately, unlike a generator
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference