generator iterator

In Python, a generator iterator is an iterator that results from calling a generator function, which you define with the yield keyword. This iterator lets you iterate over a data stream one item at a time. It stores only the current item in memory instead of the entire data stream.

Generator iterators are a memory-efficient way to handle large data sets or streams, as they generate values on the fly and only keep track of the current state.

Example

Here’s a quick example of a generator function that returns a generator iterator:

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

>>> counter = count_generator(5)
>>> counter
<generator object count_generator at 0x102e39560>

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

In this example, count_generator() is a generator function. It returns a generator iterator object that yields numbers from 0 up to the specified limit value. When you call count_generator(5), it returns a generator iterator that you can iterate over to get each number in sequence.

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 15, 2025 • Reviewed by Leodanis Pozo Ramos