What are Comprehensions?
Comprehensions are concise ways to create lists, dictionaries, and sets. They're more readable and often faster than equivalent loops.
List Comprehensions
Create lists concisely:
# Traditional way
squares = []
for x in range(10):
squares.append(x**2)
# List comprehension
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, ...]
With Conditions
Add filters:
# Even squares only
evens = [x**2 for x in range(10) if x % 2 == 0]
# Numbers greater than 5
filtered = [x for x in range(10) if x > 5]
Dictionary Comprehensions
Create dictionaries:
# Square mapping
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# With condition
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
Set Comprehensions
Create sets:
# Unique squares
unique = {x**2 for x in range(-5, 6)}
# {0, 1, 4, 9, 16, 25}
Nested Comprehensions
Create nested structures:
# Matrix
matrix = [[i*j for j in range(3)] for i in range(3)]
# [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
Best Practices
- Use for simple transformations: Keep comprehensions readable
- Avoid complex logic: Use loops for complex operations
- Prefer over loops: More Pythonic and often faster
- Don't nest too deeply: Keep it to 2-3 levels max
Next Steps
Learn about generators and advanced lambda.