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:

 1class Counter:
 2    def __init__(self, start, end):
 3        self.current = start
 4        self.end = end
 5
 6    def __iter__(self):
 7        return self
 8
 9    def __next__(self):
10        if self.current > self.end:
11            raise StopIteration
12        else:
13            self.current += 1
14            return self.current - 1
15
16# create an iterator object
17counter = Counter(1, 5)
18
19# print all the numbers
20for num in counter:
21    print(num)

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.

1temperatures = ['22C', '24C', '26C']
2enumerate_temperatures = enumerate(temperatures)
3
4print(next(enumerate_temperatures))

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.