Introduction
List comprehensions provide a concise way to create lists based on existing sequences.
Basic Syntax
# Traditional loop
squares = []
for i in range(10):
squares.append(i ** 2)
# List comprehension
squares = [i ** 2 for i in range(10)]
# With condition
evens = [i for i in range(20) if i % 2 == 0]
Nested Comprehensions
# 2D matrix
matrix = [[i * j for j in range(5)] for i in range(5)]
# Flatten nested list
nested = [[1, 2], [3, 4], [5, 6]]
flat = [item for sublist in nested for item in sublist]
Advanced Patterns
# With multiple conditions
result = [x for x in range(100) if x % 2 == 0 if x % 5 == 0]
# With if-else (ternary)
labels = ["even" if x % 2 == 0 else "odd" for x in range(10)]
# Dictionary comprehension
word_lengths = {word: len(word) for word in ["hello", "world"]}
# Set comprehension
unique_lengths = {len(word) for word in ["hi", "hello", "world"]}
Generator Expression
# Instead of creating full list
sum_of_squares = sum(x**2 for x in range(1000000))
Practice Problems
- Generate list of prime numbers using comprehension
- Matrix transposition using comprehension
- Flatten dictionary of lists
- Filter and transform data simultaneously
- Create nested structure with comprehension