Iterators in Python

Why iterators in Python! Just have a look below.

Therefore, let us define iterators. They are objects that contain values. Most common data types like Lists, Tuples, Dictionaries are examples of default iterators.

Wait for a minute! We will take an example to iterate from 1 to n.

Well, there are two important conditions for any object to be an iterator. Any iterator implements these two magic methods.

  1. __iter__(): It is an initializer of iterator just like __init__() written in a class. It also returns object that contains __next__() .
  2. __next__(): It returns the next value in the iterable.

Understand Iterators in Python

Now, we will try to understand how this works by implementing step by step.

Step 1: Create Iterators in Python

class iterate:
    def __iter__(self):
        self.x = 1        # means that the iteration is going to start from 1
        return self
    def __next__(self):
        num = self.x          # storing present value of x
        

Step 2: Now, that we have created a class with those 2 magic methods, let’s make the __init__() method.

def __init__(self,max_limit):
       self.num = max_limit

Step 3: It’s time to proceed for the extension of the __next__() method to make sure the iteration is finite

def __next__(self):
        num = self.n          # storing present value of x
        if num > self.num:      # for finite iteration
            raise StopIteration
        else:
            self.n = num + 1    # incrementing for next value
            return num

Putting all things together we are able to create an Iterate class. Let’s have a look.

class iterate:
    def __init__(self,max_limit):     # the max_limit set by the user.
        self.num = max_limit
    
    def __iter__(self):
        self.n = 1        # means that the iteration is going to start from 1
        return self
    
    def __next__(self):
        num = self.n          # storing present value of x
        if num > self.num:      # for finite iteration
            raise StopIteration
        else:
            self.n = num + 1    # incrementing for next value
            return num
        

Step 4: Looping through Iterators. A “for-in” loop is used to traverse all the values

for i in iterate(10): # This will call the methods __iter__() once and __next__() continuosly upto max_limit
    print(i)

 

Step 5: Final Code to iterate from 1 to n using a user-defined class

class iterate:
    def __init__(self,max_limit):     # the max_limit set by the user.
        self.num = max_limit
    
    def __iter__(self):
        self.n = 1        # means that the iteration is going to start from 1
        return self
    
    def __next__(self):
        num = self.n          # storing present value of x
        if num > self.num:      # for finite iteration
            raise StopIteration
        else:
            self.n = num + 1    # incrementing for next value
            return num
        
    
for i in iterate(10):   # This will call the methods __iter__() once and __next__() continuosly upto max_limit
    print(i)

 

As we have understood how finite iterators work in Python. Now let’s move to understand Infinite Iterators.

Infinite Iterators in Python

Normally the Iterator object exhaust after some time as we usually use finite values. But it is not necessary, the iterators that never exhausts are known as Infinite Iterators.

Simply, Infinite Iterators can be made if we exclude StopIteration from the above code.

Example:

class iterate:            # designed to show infinite iterators.
    
    def __iter__(self):
        self.n = 1        # means that the iteration is going to start from 1
        return self
    
    def __next__(self):
        num = self.n          # storing present value of x
        self.n = num + 1    # incrementing for next value forever
        return num              
        
    
for i in iterate():   # This will call the methods __iter__() once and __next__() INFINETLY
    print(i)

 

Hope, This clears the idea of how iterators work in Python and their traversal using for-in loop.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *