Iterator
What is an Iterator?
In Python, an iterator is an object that contains a countable number of values. In more simple terms, it can be seen as a device that can remember its state, remembering which computation it is in and returning the next value when needed. This is done with the help of two fundamental methods available to an iterator, __iter__()
and __next__()
.
Iterable vs. Iterator
Before we get into iterators, let’s define an iterable. An iterable is an object capable of returning its elements one at a time. Running a for
loop over a list data type is a typical example of utilizing an iterable. An iterator is used to get the next value in an iterable.
Creating an Iterator
Creating an iterator in Python requires the implementation of the methods __iter__()
and __next__()
in the object’s definition. The __iter__()
method returns the iterator object itself, while __next__()
returns the next value from the iterator.
Here is an example showing the creation of an iterator:
In this example, the Counter
class defines the iterators for the object. The for
loop uses the iterator to print all the numbers from 1 to 5.
Built-in Iterator Functions
Python includes several built-in functions that receive iterable and return iterators, such as enumerate()
, filter()
, map()
, and zip()
.
Here you can see an example utilizing enumerate()
function that returns an iterator.
Note
Not all iterables are iterators. Lists, tuples, dictionaries, and sets are iterable but not iteration objects. They can’t produce an immediate next value but can produce an iterator with the iter()
function.