Python Generators · Examples
Core Python

Python Generators Examples

Short, runnable programs that show python generators, iterators and yield in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Generators, Iterators and yield lesson.

1An endless generator of ticket numbers

A generator can run forever with while True, because it only does work when asked. The caller decides how many values to take.

An endless generator of ticket numbers
def ticket_numbers(start):
    n = start
    while True:
        yield f"T-{n:03d}"
        n += 1

tickets = ticket_numbers(7)
print(next(tickets))
print(next(tickets))
for _ in range(3):
    print("Issued", next(tickets))
Expected outputT-007
T-008
Issued T-009
Issued T-010
Issued T-011

2Fibonacci numbers on demand

The generator keeps a and b between calls, so each value is built from the previous two without storing the whole sequence.

Fibonacci numbers on demand
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

for number in fibonacci():
    if number > 100:
        break
    print(number, end=" ")
print()
Expected output0 1 1 2 3 5 8 13 21 34 55 89

3A generator pipeline

Each step is a generator that feeds the next one. Values flow through one at a time, so this works the same for 5 lines or 5 million.

A generator pipeline
raw = ["12.50", "oops", "8", "", "20.25"]

cleaned = (r.strip() for r in raw)
numeric = (r for r in cleaned if r.replace(".", "", 1).isdigit())
amounts = (float(r) for r in numeric)

print("Total:", sum(amounts))
Expected outputTotal: 40.75

4What a for loop really does

This while loop does exactly what for letter in word: does behind the scenes: get an iterator, call next() repeatedly, stop on StopIteration.

What a for loop really does
word = "code"
it = iter(word)

while True:
    try:
        letter = next(it)
    except StopIteration:
        break
    print(letter.upper(), end="")
print()
Expected outputCODE

Practise next

Python Generators, Iterators and yield exercises → Back to the lesson

Python List Comprehensions examplesPython Iterators examplesPython itertools examplesPython File Handling examples