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:
>>> 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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Iterators and Iterables in Python: Run Efficient Iterations (Tutorial)
- Asynchronous Iterators and Iterables in Python (Tutorial)
- Python Generators 101 (Course)
- How to Use Generators and yield in Python (Quiz)
- Efficient Iterations With Python Iterators and Iterables (Course)
- Iterators and Iterables in Python: Run Efficient Iterations (Quiz)
- Asynchronous Iterators and Iterables in Python (Quiz)