Advanced Comprehensions
Nested comprehensions, conditional logic, and performance implications.
Overview
Master advanced comprehension patterns.
Nested Comprehensions
# 2D list comprehension
matrix = [[i*3 + j + 1 for j in range(3)] for i in range(3)]
print(matrix) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Flatten nested list
nested = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for sublist in nested for num in sublist]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Dictionary comprehension with transformation
words = ["hello", "world", "python"]
word_lengths = {word: len(word) for word in words}
print(word_lengths) # {'hello': 5, 'world': 5, 'python': 6}
# Set comprehension
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique_squares = {x**2 for x in numbers}
print(unique_squares) # {16, 1, 4, 9}
# Conditional in comprehension
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Nested conditional
result = ["even" if x % 2 == 0 else "odd" for x in range(10)]
print(result) # ['even', 'odd', 'even', 'odd', ...]
Generator Expressions
# Lazy evaluation
gen = (x**2 for x in range(1000000))
print(next(gen)) # 0
print(next(gen)) # 1
# Memory efficient
sum_of_squares = sum(x**2 for x in range(1000000))
# Chained operations
filtered = (x for x in range(100) if x % 2 == 0 if x % 3 == 0)
print(list(filtered)) # [0, 6, 12, 18, ...]
Performance Comparison
import timeit
# List comprehension vs loop
setup = "data = list(range(1000))"
list_comp = timeit.timeit(
"[x**2 for x in data]",
setup=setup,
number=1000
)
loop = timeit.timeit("""
result = []
for x in data:
result.append(x**2)
""", setup=setup, number=1000)
print(f"List comprehension: {list_comp:.4f}s")
print(f"Loop: {loop:.4f}s")
Practice
Create a nested dictionary comprehension for a shopping cart.