List Comprehension
Basic Syntax
List comprehensions provide a compact and readable way to build lists in Python. They are enclosed in square brackets, contain an expression followed by a for clause, and may include optional conditions. They are often clearer and shorter than using map(), filter(), or lambda functions.
Example
# Basic comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
# With condition
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
# Nested loops
pairs = [(x, y) for x in [1, 2] for y in [3, 4]] # [(1, 3), (1, 4), (2, 3), (2, 4)]
Output
[0, 1, 4, 9, 16] [0, 2, 4, 6, 8] [(1, 3), (1, 4), (2, 3), (2, 4)]
Advanced Patterns
Comprehensions are not limited to lists. Variations include dictionary and set comprehensions. They can also be nested for multidimensional operations.
Example
# Matrix transposition
matrix = [[1, 2], [3, 4], [5, 6]]
transposed = [[row[i] for row in matrix] for i in range(2)]
# Dictionary comprehension
names = ['Alice', 'Bob']
name_lengths = {name: len(name) for name in names}
# Set comprehension
unique_lengths = {len(name) for name in names}
print(transposed)
print(name_lengths)
print(unique_lengths)
Output
[[1, 3, 5], [2, 4, 6]] {'Alice': 5, 'Bob': 3} {3, 5}
Performance Benefits
List comprehensions are generally more efficient than equivalent constructs using map() and filter(), because they are implemented in C under the hood. They improve readability and performance while reducing the need for lambda functions.
Example
from timeit import timeit
# Compare comprehension with map/lambda
print("Comprehension:", timeit("[x**2 for x in range(100)]"))
print("Map:", timeit("list(map(lambda x: x**2, range(100)))"))
ℹ️ Note: In most cases, comprehensions run 10–20% faster than equivalent map/filter code, while being easier to read.