Skip to content

Module 10 · Comprehensions and Advanced Iteration — topic 11 of 13

Generators

Generator functions that produce values one at a time with yield: how they pause and resume, infinite generators, reading data in pipelines, and why they are simpler than iterator classes.

Beginner 12 min read·Lesson 155 of 306 in Python Programming

Learning objectives

  • Write generator functions
  • Explain how a generator pauses and resumes
  • Use generators for large or infinite sequences

Definition

A generator is a function that contains yield. Calling it returns a generator object (an iterator); each next() runs the function until the next yield, returns that value and pauses, keeping all local state until it is resumed.

Introduction

The Countdown iterator class needed three methods and a state variable. The generator version is four lines: a loop that yields each value. Python handles __iter__, __next__ and StopIteration for you.

Why it matters

Generators are the standard way to produce sequences lazily: reading big files, generating IDs, streaming API pages or building data pipelines.

Detailed explanation

Any function containing yield is a generator function. Calling it doesn't run the body; it returns a generator object.

Each next() resumes the body from where it last paused and runs until the next yield, which hands a value back and pauses again. Local variables keep their values between steps.

When the function body finishes (or hits return), the generator raises StopIteration automatically.

Generators can be infinite (while True: yield ...) because values are only produced when requested; combine them with itertools.islice or a break.

Like all iterators, a generator object is single-use. Call the generator function again to start over.

Syntax

Python
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(3):
print(x)
  • yield makes a function a generator.
  • Calling it returns a generator object.
  • Each next() resumes until the next yield.

Code examples

A generator function

Python
def countdown(n):
while n > 0:
yield n
n -= 1
gen = countdown(3)
print(type(gen).__name__)
print(list(gen))
print(list(countdown(5)))
Output
generator
[3, 2, 1]
[5, 4, 3, 2, 1]

Pausing and resuming

Python
def steps():
print("start")
yield 1
print("after first yield")
yield 2
print("end")
g = steps()
print("created")
print(next(g))
print(next(g))
print(next(g, "finished"))
Output
created
start
1
after first yield
2
end
finished

More examples

Infinite generators and pipelines

Python
from itertools import islice
def ids(prefix):
n = 1
while True: # infinite, but lazy
yield f"{prefix}{n:04d}"
n += 1
def read_records(lines):
for line in lines:
line = line.strip()
if line and not line.startswith("#"):
yield line.split(",")
def paid_totals(records):
for name, amount, status in records:
if status == "paid":
yield name, int(amount)
print(list(islice(ids("ORD"), 3)))
log = ["# orders", "Asha,1200,paid", "", "Ravi,300,pending", "Meera,5400,paid"]
for name, amount in paid_totals(read_records(log)):
print(name, amount)
Output
['ORD0001', 'ORD0002', 'ORD0003']
Asha 1200
Meera 5400

Step-by-step explanation

  • ids never ends, but islice takes just three values, so only three are ever computed.
  • read_records yields one cleaned record at a time, skipping comments and blank lines.
  • paid_totals consumes records and yields only paid ones — each stage handles one item before the next is read.
  • The pipeline would work unchanged on a file object with millions of lines.

Expected output

Running “Infinite generators and pipelines” prints exactly:

TextOutput
['ORD0001', 'ORD0002', 'ORD0003']
Asha 1200
Meera 5400

Practical applications

  • Reading log files lazily line by line.
  • Paginating through API results.
  • Generating test data or unique identifiers on demand.

Best practices

  • Use generators instead of iterator classes.
  • Build data pipelines from small generator functions.
  • Bound infinite generators with islice or a break.

Common mistakes

Calling a generator and expecting it to run

Avoid

def setup():
print("setting up")
yield
setup() # prints nothing

Prefer

next(setup()) # or iterate over it

Calling a generator function only creates the generator; the body runs when it is iterated.

Using return to produce values

Avoid

def evens(n):
for i in range(n):
if i % 2 == 0:
return i

Prefer

def evens(n):
for i in range(n):
if i % 2 == 0:
yield i

return ends the function after the first value; yield produces each value in turn.

Important notes

  • yield from other_iterable delegates to another iterable, yielding all its values.

Key takeaways

  • A function with yield returns a generator object.
  • It pauses at each yield and keeps its local state.
  • Generators are lazy, single-use and can be infinite.

Try it yourself

  1. 1
    Write fibonacci() as an infinite generator and print the first 10 values.
  2. 2
    Write a generator that yields the lines of a list that contain a given keyword.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions cover the “Comprehensions and Advanced Iteration” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module