Lesson 31 of 35Python
Python · Lesson 31 · 25 minutes
Generators and yield
What you'll learn
- Write functions with
yield - Understand why generators save memory
- Use generators with
next(), for andsum()
Producing values one after another
A normal function gives back one value with return and is then finished. A generator uses yield: it produces a value, pauses – and carries on exactly there next time.
def countdown(start):
while start > 0:
yield start
start -= 1
yield "Liftoff!"
for value in countdown(3):
print(value)Press Steps: you can see Python jumping back and forth between the loop and the generator.
Step by step with next()
With next() you fetch the next value yourself:
def colours():
yield "red"
yield "amber"
yield "green"
traffic_light = colours()
print(next(traffic_light))
print(next(traffic_light))
print(next(traffic_light))One more next(traffic_light) would raise a StopIteration error – the generator is empty.
Why generators?
A list with a million numbers needs a lot of memory. A generator only calculates each number when it’s needed. With round brackets there are even generator expressions:
total = sum(x * x for x in range(1_000_000))
print(total)No list is built – and still the right result comes out.
Remember: If you see
yieldin a function, it’s a generator. You can use generators inforloops, withlist(),sum()ornext().
Quick check
Before you start the task: what does this program print? Type your guess – then Python works it out.
def squares(n):
for i in range(n):
yield i * i
g = squares(4)
print(next(g), next(g))
print(list(g))Your task
Your turn
Write a generator fibonacci(n) that produces the first n Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, … (every number is the sum of the two before it). Use yield – no list.
def fibonacci(n):
# a and b are the last two numbers
a, b = 0, 1
# produce n numbers with yield
print(list(fibonacci(10)))- Something to think about
First
yielda, then calculate on with a, b=b, a+b. - Which command helps?
A generator uses
yieldinstead of return. - Gap code – fill in the ___
def fibonacci(n): # a and b are the last two numbers a, b = 0, 1 for _ in ___: ___ a, b = ___ print(list(fibonacci(10)))
Solve it without hints to earn a ⭐ on your progress page.
Show solution🔒 Unlocks after all hints or 2 checks
Try it yourself first – mistakes teach you the most. Here is one possible solution:
def fibonacci(n):
# a and b are the last two numbers
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(fibonacci(10)))