Python List Comprehensions Explained
Write concise, Pythonic code with list comprehensions — from basic syntax to nested comprehensions and when to use alternatives.
What Are List Comprehensions?
List comprehensions provide a concise way to create lists in Python. They replace the pattern of creating an empty list, looping, and appending with a single expressive line.
# Traditional approach
squares = []
for x in range(10):
squares.append(x ** 2)
# List comprehension
squares = [x ** 2 for x in range(10)]
Basic Syntax
The general form is: [expression for item in iterable if condition]
# Transform
names = ["ada", "bob", "cat"]
upper = [name.upper() for name in names]
# ["ADA", "BOB", "CAT"]
# Filter
numbers = range(20)
evens = [n for n in numbers if n % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Transform + Filter
big_squares = [x ** 2 for x in range(20) if x ** 2 > 50]
# [64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361]
Conditional Expressions
You can include if/else in the expression part (before the for):
labels = ["even" if n % 2 == 0 else "odd" for n in range(5)]
# ["even", "odd", "even", "odd", "even"]
Nested Comprehensions
Flatten nested structures or create combinations:
# Flatten a matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Cartesian product
colors = ["red", "blue"]
sizes = ["S", "M", "L"]
combos = [(c, s) for c in colors for s in sizes]
Dict and Set Comprehensions
# Dict comprehension
word_lengths = {word: len(word) for word in ["hello", "world", "python"]}
# {"hello": 5, "world": 5, "python": 6}
# Set comprehension
unique_lengths = {len(word) for word in ["hello", "world", "hi"]}
# {2, 5}
When Not to Use Comprehensions
Comprehensions should enhance readability, not harm it. If your comprehension exceeds one line or requires complex logic, a regular loop is clearer. Side effects (like printing or writing files) belong in loops, not comprehensions.
Performance
List comprehensions are slightly faster than equivalent for-loops because the append operation is optimized internally. For large datasets where you do not need the full list in memory, consider generator expressions (using parentheses instead of brackets).
Summary
List comprehensions are one of Python’s most beloved features. They are concise, readable, and Pythonic. Start simple, and reach for them whenever you find yourself writing the append-in-a-loop pattern.