iterator
In Python, an iterator is an object that adheres to the iterator protocol, which consists of the methods .__iter__()
and .__next__()
. This type of object allows you to traverse (or “iterate”) through all the items in a data stream.
Technically, an iterator is any object that implements two special methods: .__iter__()
which returns the iterator object itself, and .__next__()
which returns the next value and raises a StopIteration
exception when there are no more items to return.
The built-in functions iter()
and next()
provide a standard way to work with iterators in Python:
iter()
creates an iterator from an iterable object. It calls the object’s.__iter__()
method and returns an iterator that will generate each item in the sequence. You can think ofiter()
as initializing a traversal through your data.next()
advances the iterator to retrieve the next value by calling the iterator’s.__next__()
method. Each call tonext()
returns the next item in the sequence until all items are exhausted, at which point it raisesStopIteration
. This is how Python keeps track of its position as it moves through your data.
Iterators are the foundation of Python’s for
loops and comprehensions, allowing you to process sequences of data efficiently without loading the entire sequence into memory at once. Common examples of iterators include file objects, enumerate()
objects, and generator expressions.
Python Iterator - Basic Example
>>> # Lists are iterable
>>> my_list = [1, 2, 3]
>>> # Create iterator from iterable
>>> iterator = iter(my_list)
>>> iterator
<list_iterator object at 0xffffa4754c10>
>>> # Consume values from the iterator
>>> next(iterator)
1
>>> next(iterator)
2
>>> next(iterator)
3
>>> # Exhausted iterator raises StopIteration
>>> next(iterator)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
These functions form the underlying mechanism that Python’s for
loops use behind the scenes. When you write a for
loop, Python automatically calls iter()
to create an iterator and then repeatedly calls next()
until it encounters StopIteration
:
>>> my_list = [1, 2, 3]
>>> for item in my_list:
>>> print(item)
1
2
3
Related Resources
Tutorial
Iterators and Iterables in Python: Run Efficient Iterations
In this tutorial, you'll learn what iterators and iterables are in Python. You'll learn how they differ and when to use them in your code. You'll also learn how to create your own iterators and iterables to make data processing more efficient.
For additional information on related topics, take a look at the following resources:
- Asynchronous Iterators and Iterables in Python (Tutorial)
- How to Use Generators and yield in Python (Tutorial)
- Efficient Iterations With Python Iterators and Iterables (Course)
- Iterators and Iterables in Python: Run Efficient Iterations (Quiz)
- Asynchronous Iterators and Iterables in Python (Quiz)
- Python Generators 101 (Course)
- How to Use Generators and yield in Python (Quiz)