🔄 Quick Recap (Day 16)
You learned to isolate projects with virtual environments.
You managed dependencies with pip and froze requirements for sharing.
🎯 What You’ll Learn Today
What a list comprehension is and how it simplifies creating lists.
How to add conditions inside comprehensions.
What a generator is and why it’s memory-efficient.
How to write generator expressions and custom generator functions.
📖 List Comprehensions: Quick Lists
A list comprehension combines a loop and optional condition into a single, concise expression.
Standard loop:
squares = []
for x in range(1, 6):
squares.append(x * x)
print(squares)List comprehension:
squares = [x * x for x in range(1, 6)]
print(squares)Both produce:
[1, 4, 9, 16, 25]Adding Conditions
Include an if to filter items:
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]📖 Generators: Lazy Sequences
Generators yield items one at a time, saving memory for large sequences.
Generator Expression
Similar syntax to list comprehensions but with parentheses:
big_squares = (x * x for x in range(1, 1000000))
print(next(big_squares)) # 1
print(next(big_squares)) # 4Only computes values as requested.
Generator Function
Use yield inside a function:
def countdown(n):
while n > 0:
yield n
n -= 1
for number in countdown(5):
print(number)Outputs:
5
4
3
2
1🧙♂️ Take the Wand and Try Yourself
Create a file
comp_gen.py.List comprehension:
Generate a list of the cubes of numbers 1–10.
Filter to include only cubes divisible by 3.
Generator expression:
Create a generator for the same cubes.
Use
next()to print the first three values.
Generator function:
Write
even_numbers(n)that yields even numbers up ton.Use a loop to print all evens up to 10.
Solution Example (comp_gen.py):
# comp_gen.py
# List comprehension with condition
cubes = [x**3 for x in range(1, 11) if (x**3) % 3 == 0]
print(cubes) # [27, 216, 729]
# Generator expression
cube_gen = (x**3 for x in range(1, 11))
print(next(cube_gen)) # 1
print(next(cube_gen)) # 8
print(next(cube_gen)) # 27
# Generator function
def even_numbers(n):
for x in range(1, n+1):
if x % 2 == 0:
yield x
for e in even_numbers(10):
print(e)Expected output:
[27, 216, 729]
1
8
27
2
4
6
8
10Run:
python comp_gen.pyOnce your output matches, you’ve mastered list comprehensions and generators!
Up next: Day 17: Standard Library Deep Dive