Python Generator in a for Loop: StopIteration Explained
A Python generator in a for loop hands over one value per pass. The loop ends when the generator function finishes, which Python signals with StopIteration.
You will loop over a generator, see what ends the loop, and learn why a generator works only once. Prerequisites: while loops and Infinite Generators in Python: Running State. No imports are needed.
Loop over a generator with for
A for loop makes the next() requests for you.
def evens(limit): number = 2 while number <= limit: yield number number += 2for value in evens(8): print(value)print("done")This prints 2, 4, 6, 8, then done. When number passes limit, the while loop ends. The function body ends with it, so the generator is finished and the for loop stops.
StopIteration ends the loop
A finished generator raises StopIteration when asked for another value.
def evens(limit): number = 2 while number <= limit: yield number number += 2values = evens(4)print(next(values))print(next(values))print(next(values)) # this line raises StopIteration: the function has endedThis prints 2 and 4, then stops with the error. A for loop catches StopIteration and ends quietly. With next() you must count your own requests.
Choose between for and next()
Use for when you want every value. Use next() when you want one value now and the rest later.
An infinite generator never raises StopIteration. A for loop over it needs its own exit.
def counting(): number = 1 while True: yield number number += 1for value in counting(): if value > 3: break print(value)This prints 1, 2, 3. Without the break, the loop would never end.
A generator can be looped over only once
A finished generator stays finished. A second loop over it gets nothing.
def evens(limit): number = 2 while number <= limit: yield number number += 2values = evens(4)for value in values: print("first loop", value)for value in values: print("second loop", value)print(list(evens(4)))Only the first loop prints. Calling evens(4) again makes a new generator that starts from 2.
Note: These generators are small so the output stays short. The rule is the same for a generator that reads a million rows.
See also: Python Iterators, Python Generator close(): Stopping a Generator.
Your turn
Write halves(start). It yields start, then half of it (use //), and ends by itself when the number reaches 0. Print every value of halves(40) with a for loop, then print done.
40 20 10 5 2 1 done
# Define halves(start), loop over halves(40) with for, then print done.