Writing an iterator by hand is laborious. Python offers a shortcut: generator functions. A function that uses yield instead of return becomes a generator.
Your first generator
def countdown(n):
while n > 0:
yield n
n -= 1
gen = countdown(3)
print(next(gen)) # 3
print(next(gen)) # 2
print(next(gen)) # 1
When calling countdown(3) nothing is executed yet: you get a generator object. Each next runs the function up to the next yield, returns that value and pauses, remembering the value of n and which line it was on. When another value is requested, it continues where it left off.
Looping over a generator
Since a generator is an iterator, it is used with for, with list() or with print(*gen):
for number in countdown(3):
print(number)
# 3
# 2
# 1
print(list(countdown(4))) # [4, 3, 2, 1]
print(*countdown(3)) # 3 2 1
When the function finishes, the generator raises StopIteration automatically and the for ends. Practice with Countdown with a generator.
Fibonacci as a generator
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(fibonacci(8))) # [0, 1, 1, 2, 3, 5, 8, 13]
Compare it with the version that returns a list: it would have to build the whole list in memory and return it at the end. The generator hands over each term as it is needed. Practice with Fibonacci with a generator.
yield versus return
| return | yield | |
|---|---|---|
| What it does | Returns a value and ends the function | Hands over a value and pauses the function |
| How many times | Once | Many |
| Result of the call | The value | A generator |
| State of the variables | Lost | Kept between values |
Processing data one at a time
Generators are ideal for filtering or transforming data without storing it all. For example, skipping the comments of a configuration file:
def without_comments(lines):
for line in lines:
if not line.startswith("#"):
yield line
config = ["# settings", "mode=fast", "# another note", "color=blue"]
print(list(without_comments(config))) # ['mode=fast', 'color=blue']
With a real file, lines would be the open file itself: the generator would process one line at a time, even if the file had millions. Practice with Lines without comments.
yield from: yielding a whole iterable
If you want to yield all the elements of another iterable, yield from saves you writing a loop:
def flatten(lists):
for sublist in lists:
yield from sublist
print(list(flatten([[1, 2], [3], [4, 5, 6]]))) # [1, 2, 3, 4, 5, 6]
It is equivalent to for x in sublist: yield x, but shorter. Practice with Flatten with yield from.
return inside a generator
A return without a value inside a generator ends it early:
def until_negative(numbers):
for n in numbers:
if n < 0:
return
yield n
print(list(until_negative([4, 7, -1, 9]))) # [4, 7]