Iterators in Python | Python Iterators for Looping

As the name suggests, iterators in Python are used to iterate through a sequence without knowing the index value of the elements. This sequence is called an iterable and Python has inbuilt iterable objects like Lists, Strings, Tuples, Dictionaries, Sets, etc.

In other programming languages like C, C++, Java, we use the ++ operator to iterate. But in Python, we use an iterator object. To create an iterator object in Python, you must implement two special methods, __iter__() and __next__(), collectively called the iterator protocol. The function of these methods is given below.

 

MethodDescription
__iter__()This method returns the iterator object itself and is used while using the “for” and “in” keywords.
__next__()This method returns the next value. This would return the StopIteration error once all the objects have been looped through.

Now, let us see how an iterator iterates through a list and prints the elements.

How to Use Iterators in Python

Consider the below code. Here to iterate through the given list, we have created an iterator in the name of ‘a’. iter() method is then used to convert the given list into an object which accesses one element at a time from the iterable.

#iterating through a list
list = [3, 7, 5, 9, 2]
a = iter(list)
print(a)
Output:
<listiterator object at 0x7f7f47511450>

Explanation:  Here the address of the first element is printed as the output instead of its value. But since we want o print the elements of the list, we need to use the method next() with the iterator ‘a’ as shown below.

#iterating through a list
list = [3, 7, 5, 9, 2]
a = iter(list)
print(a.__next__())
Output:
3

Note: Iterators in Python will not print all elements of the object, it will print only one element at a time.

Now, if we include another print statement, the second element of the object gets printed as shown below. Have a look at this.

#iterating through a list
list = [3, 7, 5, 9, 2]
a = iter(list)
print(a.__next__())
print(a.__next__())
Output:
3
7

How does an iterator work?

Each time the next() method is called, it preserves the value of the iterable being printed. Based on the preserved data, it will print the next value when the same function is being called again. Also, we have one more way to print the elements using the next() method and iterator. For instance, have a look at this example,
#iterating through a list
list = [3, 7, 5, 9, 2]
a = iter(list)
print(a.__next__())
print(a.__next__())
print(next(a))
Output:
3
7
5
Explanation: iterators in Python

The Advantage of using Iterators

The major advantage of using iterators is that they help save resources and make the code look cleaner. Iterators can save us a lot of memory and CPU time. Like we have seen in the above example, we can print all the even numbers without having to store them in the memory. This means we can print infinite numbers in our finite memory.

Defining/Writing your own Iterators in Python

Define our own iterators in Python is very simple. You need to implement the next() and iter() methods for this. While implementing the next() method, ensure that on reaching the end of the iterable, the method should raise StopIteration Let us now see how to create an iterator in Python that multiplies all the numbers less than n with 2.
#iterator to multiply numbers less than n with 2
class numbers:
    def __init__(self, max):
        self.max = max

    def __iter__(self):
       self.n = 0
       return self

    def __next__(self):
        if(self.n <= self.max):
            result = 2*self.n
            self.n += 1
            return result
        else:
            raise StopIteration

a = numbers(8)
for i in a:
    print(i)
Output:
0
2
4
6
8
10
12
14
16

Python Infinite Iterators

An infinite iterator in Python is the one with an infinite number of iterations. We must be extra careful when dealing with infinite iterators. Consider the following infinite iterator which prints all even numbers.

#iterator print all even numbers
class Evennumbers:

    def __iter__(self):
        self.n = 0
        return self

    def __next__(self):
        n = self.n
        self.n += 2
        return n

a = Evennumbers()
for i in a:
    print(i)

The above code will run forever. To stop it, you will have to intervene manually and stop the compiler. However, one simple way to stop it by raising a StopIteration. This simply stops the iteration when the given condition is met. For example, let us say you want to print only even numbers below 10, then here is how to raise a StopIteration.

class Evennumbers:

    def __iter__(self):
        self.n = 0
        return self

    def __next__(self):
        if (self.n < 10):
            n = self.n
            self.n += 2
            return n
       else:
            raise StopIteration

a = Evennumbers()
for i in a:
    print(i)
Output: 
0
2
4
6
8

Iterators in Python FAQs

Iterator in Python is used to iterate through a sequence without knowing the index value of the elements.

__ier()__ and __next()__ methods are used with an iterator to iterate through the given sequence.

No, an iterator will print only one element at a time using a single print statement.