Python List Comprehensions: The Complete Guide
List comprehensions are Python’s most elegant feature. They create lists in a single line where you’d normally write a for loop.
Basic Syntax
new_list = [expression for item in iterable if condition]Simple Examples
# Squares of numbers 0-9
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Even numbers only
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# String lengths
words = ["hello", "world", "python"]
lengths = [len(w) for w in words]
# [5, 5, 6]vs Traditional Loop
# Traditional
squares = []
for x in range(10):
squares.append(x**2)
# List comprehension (same result, 1 line)
squares = [x**2 for x in range(10)]With Conditionals
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Simple condition
evens = [n for n in numbers if n % 2 == 0]
# If-else (put condition before the for)
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
# ['odd', 'even', 'odd', 'even', ...]Nested Loops
# Flatten a matrix
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6]
# Cartesian product
colors = ["red", "blue"]
sizes = ["S", "M", "L"]
combinations = [(c, s) for c in colors for s in sizes]
# [('red', 'S'), ('red', 'M'), ...]Nested List Comprehensions
# Matrix transpose
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = [[row[i] for row in matrix] for i in range(3)]
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]Dictionary and Set Comprehensions
# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Set comprehension
unique_lengths = {len(w) for w in ["hi", "hello", "hey", "hi"]}
# {2, 3, 5}Generator Expressions
Same syntax but with parentheses instead of brackets. Memory efficient for large data:
# List comprehension (creates full list in memory)
squares_list = [x**2 for x in range(1000000)]
# Generator expression (lazy evaluation)
squares_gen = (x**2 for x in range(1000000))
# Use with sum, max, min
total = sum(x**2 for x in range(1000))Practical Examples
# Read file, strip newlines, skip blanks
lines = [line.strip() for line in open("file.txt") if line.strip()]
# Convert temperatures
celsius = [0, 10, 20, 30, 40]
fahrenheit = [(c * 9/5) + 32 for c in celsius]
# [32.0, 50.0, 68.0, 86.0, 104.0]
# Extract specific field from list of dicts
users = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
names = [u["name"] for u in users]
# ['Alice', 'Bob']
# Get unique characters from a string
unique = {c for c in "hello world" if c != " "}
# {'h', 'e', 'l', 'o', 'w', 'r', 'd'}When NOT to Use List Comprehensions
Complex operations — use a regular loop:
# Too complex for comprehension
processed = []
for item in data:
result = expensive_function(item)
if result and validate(result):
processed.append(transform(result))
# Don't try to compress this into a comprehensionSide effects — don’t use comprehension for printing, writing files:
# Bad (creates list [None, None, None] unnecessarily)
[print(x) for x in data]
# Good
for x in data:
print(x)Related: Learn Python string methods and error handling.