Python List Comprehensions and Generators
Ad
Python List Comprehensions and Generators
Master Python list comprehensions and generators for efficient, readable code.
List Comprehensions
Basic Syntax
# Traditional way
squares = []
for x in range(10):
squares.append(x**2)
# List comprehension
squares = [x**2 for x in range(10)]With Condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]Nested Comprehensions
matrix = [[i*j for j in range(3)] for i in range(3)]Generators
Generator Expressions
squares_gen = (x**2 for x in range(10))
for square in squares_gen:
print(square)Generator Functions
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + bBenefits
- Memory Efficient: Generators don't store all values
- Readable: More concise than loops
- Fast: Optimized for performance
- Pythonic: Follows Python best practices
When to Use
- List comprehensions for small datasets
- Generators for large datasets or infinite sequences
- Both for cleaner, more readable code
