Lesson 13 of 15
Generators
Generators
A generator is a function that produces values lazily using yield. Unlike lists, generators don't store all values in memory at once — they compute each value on demand.
yield
def count_up(start, end):
n = start
while n <= end:
yield n # produce a value, then pause
n += 1
for x in count_up(1, 5):
print(x) # 1, 2, 3, 4, 5
Infinite Generators
Generators can be infinite — only compute as many values as you need:
def naturals():
n = 0
while True:
yield n
n += 1
next()
Pull values one at a time with next():
gen = count_up(1, 3)
next(gen) # 1
next(gen) # 2
next(gen) # 3
next(gen) # raises StopIteration
Generator Expressions
Like list comprehensions, but lazy:
squares = (x**2 for x in range(1_000_000)) # no memory cost
next(squares) # 0
itertools
itertools has powerful tools for working with iterables: islice, chain, cycle, accumulate, etc.
from itertools import islice
first_five = list(islice(naturals(), 5)) # [0, 1, 2, 3, 4]
Your Task
Implement fibonacci() — an infinite generator that yields Fibonacci numbers starting from 0, 1, 1, 2, 3, 5, 8, 13, ...
Pyodide loading...
Loading...
Click "Run" to execute your code.