Python GeneratorsGet Certified
What Is a Generator?
A generator is a special kind of iterator created by a function that uses the yield keyword. Unlike an ordinary function call, calling a generator function prepares a generator object and delays execution until a value is requested. This lets the function produce a sequence gradually while keeping track of where it paused. Generators are especially useful when processing data that does not need to be stored all at once.
Generators are memory-efficient because they produce values one at a time instead of building an entire list in memory. They are perfect for large data sets, infinite sequences, and pipelines of data processing.
- yield pauses the function and hands a value back to the caller.
- The function’s local state is remembered between calls.
- Generators are iterators, so they work with
forloops,next(), and functions such assum()andlist(). - Once a generator is exhausted it cannot be restarted; call the generator function again to get a fresh one.
- Generator expressions look like list comprehensions but use parentheses and produce values lazily.
Your First Generator Function
A generator function is written much like a regular Python function, but it uses yield to provide values over time. The first call creates a generator object, and iteration begins only when you request its values. After each yielded value, execution pauses at that point and continues from the next statement when another value is requested. This makes generator functions a convenient way to describe sequences step by step.
Try It: Countdown Generator
Click Test My Code. Then change the starting number and watch the countdown.
def countdown(start):
while start > 0:
yield start
start -= 1
for n in countdown(5):
print(n)Generators Remember Their State
A generator keeps its local variables and current execution position when it pauses at a yield statement. When iteration resumes, it continues with those values rather than starting the function again. This behavior is useful for calculations that depend on earlier items, such as totals, counters, or previous readings. The example below uses that retained state to build a cumulative result.
Try It: Running Total of Game Scores
Click Test My Code. Then add more scores to the list.
def running_total(scores):
total = 0
for points in scores:
total += points
yield total
game_scores = [14, 21, 9, 28, 17]
for t in running_total(game_scores):
print(t)Using next() on a Generator
The next() function requests one value from a generator and then leaves it ready for the next request. This gives you control over how quickly a sequence is consumed, instead of processing every item in a loop. Each successful call advances the generator to its next yield statement. If no values remain, Python raises StopIteration, which signals that iteration has finished.
Try It: First Few Fibonacci Numbers
Click Test My Code. Then ask for a few more numbers with additional next() calls.
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
print(next(fib))
print(next(fib))
print(next(fib))
print(next(fib))
print(next(fib))
print(next(fib))Generator Expressions
A generator expression provides a compact way to create a generator from an existing iterable. Its syntax resembles a list comprehension, but parentheses make the result lazy rather than building all values immediately. The calculation for each item happens as the generator is consumed, which can reduce memory use for large sequences. Use this form when the transformation is simple enough to fit clearly on one line.
Try It: Squares of Temperatures
Click Test My Code. Compare the memory behavior by thinking about a very long list of temperatures.
temps = [32, 45, 58, 71, 84]
squares = (t * t for t in temps)
print(next(squares))
print(next(squares))
print(list(squares))Filtering with a Generator
A generator can apply a condition before passing values to the code that consumes it. Instead of creating a separate collection of matching items, it checks each record and yields only those that satisfy the condition. This approach is useful for processing logs, student results, measurements, or other datasets that may contain many entries. You can also make the cutoff or condition configurable through function arguments.
Try It: High-Scoring Students
Click Test My Code. Then change the cutoff score.
def high_scorers(records, cutoff=85):
for name, score in records:
if score >= cutoff:
yield name
students = [("Liam", 92), ("Olivia", 78), ("Noah", 88), ("Emma", 95), ("Ava", 81)]
for student in high_scorers(students):
print(student)Chaining Generators
Small generator functions can be connected so that the output of one becomes the input of another. Each stage can focus on a single task, such as cleaning text, converting values, or selecting records that meet a condition. Because values move through the stages as they are requested, the pipeline avoids creating temporary lists between steps. This structure can make data-processing code easier to test, reuse, and maintain.
Try It: Clean and Convert Temperatures
Click Test My Code. Then add another temperature reading.
def clean(temps):
for t in temps:
yield int(t.strip())
def to_celsius(temps):
for f in temps:
yield round((f - 32) * 5 / 9, 1)
def warm_days(temps, threshold=20):
for c in temps:
if c >= threshold:
yield c
raw = [" 32 ", "68", " 86", "50", "95"]
pipeline = warm_days(to_celsius(clean(raw)))
print(list(pipeline))Generators vs Lists – Memory Comparison
Lists store all their elements in memory, while generators calculate or retrieve each value when it is needed. This difference matters when a sequence contains many items or when only part of the result will be used. A generator does not automatically make every operation faster, but it can avoid the memory cost of an intermediate collection. The example compares two ways to calculate the same total so you can see that the result can remain unchanged.
Try It: Sum of Squares
Click Test My Code. Imagine the range is millions of numbers instead of a few dozen.
numbers = range(1, 11)
list_version = sum([n * n for n in numbers])
gen_version = sum(n * n for n in numbers)
print(list_version)
print(gen_version)
print(list_version == gen_version)Practical Example: Reading a Stream of Names
A stream is a sequence of values that can be handled as they become available instead of being collected in full first. Generators make this pattern practical by passing each item through the program only when the next value is requested. You can use the same approach with file lines, incoming records, or other sources that are read progressively. In this example, one generator supplies names and another transforms them into greetings.
Try It: Process a Student Roster Lazily
Click Test My Code. Then add more names to the source list.
def name_stream(names):
for name in names:
yield name
def greet(names):
for n in names:
yield f"Hello, {n}!"
roster = ["Ava", "Liam", "Mia", "Noah", "Emma", "Jackson"]
greetings = greet(name_stream(roster))
print(next(greetings))
print(next(greetings))
print(next(greetings))Tip: When you only need to walk through data once, prefer a generator over a list. You save memory and often write clearer code. If you need random access or multiple passes, convert the generator to a list with list(gen).
Common Mistakes with Generators
Generators are straightforward once you understand that they produce values on demand and normally move in one direction. Many problems arise when code treats a generator like a reusable list or expects all of its values to be available immediately. It is also important to distinguish between pausing with yield and finishing a function with return. Review these common issues to make generator-based code more predictable.
- Trying to reuse an exhausted generator: After a for loop finishes, the generator is spent. Call the generator function again to obtain a fresh generator.
- Using return instead of yield: return ends the generator permanently. Use yield when you want to produce a value and continue later.
- Forgetting that generator expressions are lazy: The expression inside the parentheses is not evaluated until you pull a value.
- Building a list when a generator would suffice: sum(n*n for n in data) is usually better than sum([n*n for n in data]).
- Expecting len() or indexing to work: Generators do not support len(), indexing, or slicing because they do not know their full contents in advance.
- Mixing yield and return with a value: In modern Python a return with a value inside a generator raises StopIteration with that value, which most for loops ignore. Prefer a bare return or simply fall off the end.
Good Habits for Writing Generators
Well-designed generators are usually small, focused, and clear about the values they produce. Give each function one responsibility so that different stages can be combined when a task becomes more complex. Choose a generator when callers can process values sequentially, and use a concrete collection when they need repeated access to stored results. These habits help keep lazy data processing readable without making the code unnecessarily complicated.
- Name generator functions with verbs that describe the stream they produce (countdown, running_total, high_scorers).
- Keep each generator focused on one transformation; chain several small generators rather than writing one huge function.
- Use generator expressions for simple one-line transformations.
- Document the fact that a function is a generator so callers know it returns an iterator, not a list.
- When you need the full result more than once, materialize it with list() or tuple() at the point you need it.
- Remember that generators are single-pass; design your code accordingly.
Key Takeaways
Generators offer a practical way to create and process sequences without constructing every result in advance. Their behavior is built around pausing at yield and resuming when another value is requested. They work naturally with Python iteration tools and can be combined to form data-processing pipelines. Keep these main ideas in mind when deciding whether a generator is a good fit for a task.
- A generator function uses yield instead of return and produces an iterator.
- Generators pause and resume, remembering their local state between yields.
- They are memory-efficient because they produce one value at a time.
- Generator expressions (parentheses) are the lazy cousins of list comprehensions.
- You can chain generators into processing pipelines without intermediate lists.
- Once exhausted, a generator cannot be restarted; call the function again.
- Prefer generators when you process large or infinite data streams.
Frequently Asked Questions
The questions below address common points that arise when you start using Python generators. They cover how generators differ from ordinary functions and lists, how their values are consumed, and where generator expressions fit in. Use the answers as a quick reference when working through the examples or debugging your own code. Each answer focuses on the practical behavior you are likely to encounter.
What is the difference between a generator and a normal function?
A normal function runs to completion and returns a single value (or None). A generator function contains yield; calling it returns a generator object that produces a sequence of values over time, pausing after each yield.
When should I use a generator instead of a list?
Use a generator when the full sequence is large, infinite, or only needs to be processed once. Use a list when you need random access, multiple passes, or the ability to know the length in advance.
Can I convert a generator to a list?
Yes. list(my_generator) consumes the generator and builds an ordinary list that contains every remaining value. After that call the generator is exhausted.
What is a generator expression?
A generator expression looks like a list comprehension but uses parentheses: (x*x for x in data). It creates a generator object instead of a list, so values are produced lazily.
Why does my generator seem to stop early?
Generators are exhausted after one complete pass. If you try to loop over the same generator object a second time, nothing happens. Create a new generator by calling the generator function again.
Can a generator produce an infinite sequence?
Yes. Because values are produced on demand, a generator can run forever (for example a Fibonacci generator or a sensor stream). The caller decides when to stop pulling values.
Do generators work with sum(), max(), and other built-ins?
Yes. Any function that accepts an iterable can accept a generator. sum(n*n for n in range(1000000)) is both concise and memory-friendly.
Is yield the same as return?
No. return ends the function for good. yield pauses the function, returns a value, and leaves the function ready to resume from the next statement when next() is called again.