Lesson 19 of 30
List Comprehensions and Generators
Compact collection building, generator expressions, and the yield keyword.
List Comprehensions
A concise way to create lists from an iterable, optionally filtering elements:
# [expression for item in iterable if condition]
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
evens = [x for x in range(20) if x % 2 == 0]
words = ["hello", "world"]
upper = [w.upper() for w in words]
Dict and Set Comprehensions
names = ["Alice", "Bob", "Charlie"]
lengths = {name: len(name) for name in names}
# {'Alice': 5, 'Bob': 3, 'Charlie': 7}
unique_squares = {x**2 for x in [-2, -1, 0, 1, 2]}
# {0, 1, 4}
Generator Expressions
Like list comprehensions but lazy — they produce values one at a time without storing all in memory:
gen = (x**2 for x in range(1000000)) # no memory spike
print(next(gen)) # 0
print(next(gen)) # 1
yield and Generator Functions
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fibonacci(10):
print(num, end=" ")
# 0 1 1 2 3 5 8 13 21 34