To make a generator in Python, write a function that uses the yield keyword, or write a generator expression such as (x * x for x in range(5)). Calling a generator function does not run its body. It returns a generator object that produces one value at a time and remembers its state between values.
Generators are the standard tool for lazy iteration: they let you process large or endless sequences without holding everything in memory.
Any function whose body contains yield becomes a generator function. Each yield hands one value to the caller and pauses the function until the next value is requested.
A for loop calls next() on the generator repeatedly until the function ends. You can also drive it by hand:
When the function body finishes, Python raises StopIteration, which is how for loops know to stop. A generator can be consumed only once. To iterate again, call the function to create a new generator object.
A generator expression is the compact form of a simple generator. It uses parentheses instead of the square brackets of a list comprehension.
The list version [i ** 2 for i in range(1_000_000)] builds a million integers in memory first. The generator version computes each value on demand, so memory use stays almost constant. When a generator expression is the only argument of a call, as in sum(...), the extra parentheses can be dropped.
Because values are produced on demand, a generator can be infinite as long as the consumer stops at some point.
Generators also chain into pipelines. This example reads a large file one line at a time and never loads it fully:
The file is closed automatically when the generator finishes or is garbage collected.
yield from hands control to another iterable or generator and passes its values straight through. It also returns the sub-generator's return value.
Generators can receive data with send(). The value becomes the result of the yield expression inside the function.
You must advance the generator once with next() before the first send() of a real value. close() raises GeneratorExit inside the function so that finally blocks and context managers run.
Generator functions defined with async def and yield are asynchronous generators. You consume them with async for.
| Aspect | List | Generator |
|---|---|---|
| Memory | Holds all items | Holds one item at a time |
| Reuse | Iterate many times | Single pass |
Indexing and len() | Supported | Not supported |
| Start-up cost | All work done up front | Work done lazily |
Use a list when you need random access, repeated passes or the length. Use a generator when the data is large, unbounded, or only needs one pass. For stateful iteration that does not fit a function, you can also write a class with __iter__ and __next__, but a generator is almost always shorter.
return ends the function and gives back one value. yield produces a value and suspends the function, so it can resume from the same point on the next request.
A generator is exhausted after one pass. Create a new one by calling the generator function again, or collect the values in a list if you need several passes.
Yes. A return ends the iteration, and its value is attached to the StopIteration exception. It is mainly used with yield from and coroutine-style code.
Not necessarily. They save memory and avoid unneeded work, but for small data a list can be as fast or faster. Measure with timeit when speed matters.
Make a generator by writing a function with yield or by using a generator expression. Generators evaluate lazily, keep their local state between values, and can be infinite, chained or delegated with yield from. Use them whenever you process data one item at a time, and remember they can be consumed only once.