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 of iter() 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 to next() returns the next item in the sequence until all items are exhausted, at which point it raises StopIteration. 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

Python
>>> # 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:

Python
>>> my_list = [1, 2, 3]
>>> for item in my_list:
>>>     print(item)
1
2
3

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.

intermediate python

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


By Leodanis Pozo Ramos • Updated Jan. 14, 2025 • Reviewed by Dan Bader