StopIteration Examples
Short, runnable programs that show python stopiteration in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python StopIteration lesson.
1Skipping a header row with next()
Calling next() once on a file-like iterator reads the header, and the loop then continues with the remaining rows.
import io
sales = io.StringIO("item,qty\nlamp,2\ndesk,1\nchair,4\n")
header = next(sales).strip().split(",")
print(header)
total = 0
for line in sales:
total += int(line.split(",")[1])
print("units sold:", total)Expected output['item', 'qty']
units sold: 7
2A generator that can be used only once
Generators are consumed by the first pass. Recreate the generator, or build a list, to use the values again.
def even_numbers(limit):
for n in range(0, limit, 2):
yield n
evens = even_numbers(8)
print(list(evens))
print(list(evens))
print(list(even_numbers(8)))Expected output[0, 2, 4, 6]
[]
[0, 2, 4, 6]
3Pairing two lists with a shared iterator
zip() stops as soon as the shortest input is exhausted, and it handles the StopIteration internally.
names = ["Asha", "Ben", "Chen"]
scores = iter([91, 78])
for name, score in zip(names, scores):
print(name, score)Expected outputAsha 91
Ben 78
4Returning a value from a generator
The value given to return inside a generator travels on the StopIteration exception as its value attribute.
def running_total(amounts):
total = 0
for amount in amounts:
total += amount
yield total
return total
steps = running_total([5, 10, 20])
try:
while True:
print(next(steps))
except StopIteration as done:
print("final:", done.value)Expected output5
15
35
final: 35
5Cycling through a list with next()
itertools.cycle never runs out, so next() on it never raises StopIteration. Useful for round-robin assignments.
from itertools import cycle
teams = cycle(["red", "blue"])
for player in ["Asha", "Ben", "Chen", "Dev"]:
print(player, "->", next(teams))Expected outputAsha -> red
Ben -> blue
Chen -> red
Dev -> blue
Practise next
Python StopIteration exercises → Back to the lesson
Python for Loops examplesPython Exceptions: try, except, else and finally examplesPython Generators, Iterators and yield examplesPython Iterators examples