generator

In Python, a generator is a function that returns a generator iterator. The returned object allows you to iterate over data without the need to store the entire dataset in memory at once. Instead, generator iterators yield items one at a time and only when requested, making them memory efficient.

You create a generator using the yield keyword inside a function. This keyword turns the function into a generator function, which returns a generator object when called.

Generators are particularly useful when working with large datasets or streams of data where you don’t want to load everything into memory at once. They provide a lazy data generation mechanism, meaning values are computed on demand. This can significantly improve performance and reduce memory usage in your programs.

Example

Here’s an example of a generator function that returns an iterator. The resulting iterator yields numbers from 0 up to a specified limit:

Python
>>> def count_generator(limit):
...     for count in range(limit):
...         yield count
...

>>> for number in count_generator(5):
...     print(number)
...
0
1
2
3
4

In this example, count_generator() is a generator function. Calling it returns a generator object, which you can iterate over. Remember that the generator doesn’t store all the numbers at once, but generates each number on demand.

Tutorial

How to Use Generators and yield in Python

In this step-by-step tutorial, you'll learn about generators and yielding in Python. You'll create generator functions and generator expressions using multiple Python yield statements. You'll also learn how to build data pipelines that take advantage of these Pythonic tools.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 14, 2025 • Reviewed by Leodanis Pozo Ramos