Menu Close

Iterators in Python ( With Examples )

Iterators in Python

In this Python tutorial, we are going to learn all about Iterators in Python, how can we create our own iterator with the help of examples.
Basically, an Iterator in Python is an object that can be used to iterate over an iterable like list, tuple, string, list dictionary, etc.

If you are not familiar with iterators in Python, don’t worry at the last of this article, you don’t have any confusion regarding Python iterators.

What is Python Iterator ?

In Python, an Iterator is an object that presents almost everywhere. Python iterator initializing with the help of Python iter() built-in function and use Python next() method for iteration.

Iterator object has a next() method, which returns the next item of the iterable ( list, tuple, set, string, etc).

Iterable in Python

In Python, Iterable is an object. Python List, Tuple, Set, String, Dictionary all are the best example of the iterable in Python. Iterable can iterate over. It gives an iterator object when passed into the iter() method.

Example: Python Iterables


my_list = [1, 2, 3, 4, 5, 6]
my_string = 'Programming'
my_tuple = (1, 2, 3, 4, 5)

Iterator vs Iterable

Python List, Tuple, Set, String, and Dictionary all are Python iterable which can store a collection of items. Item returns an iterator object when passed into iter() function.

An iterator is an object that is used to iterate upon. Iterator object returns the next value of iterable when it is passed into Python next() function.

Technically, A Python iterator object must be implemented in two special methods that are __next__() and __iter__().

Looping Through an Iterator

In python, when we want to iterate over a sequence (sequences my be list, tuple, set, or string ) then we use it for loop like.

Example:


my_list = [1, 2, 3, 4, 5]
for i in my_list:
	print(i)

Python for loop actually creates an iterator object and executes the next() method for each loop.

Iterating through an iterator

Here we will use the next() function to iterate through all the items of an iterator, When we reach the end and there is no item to return, It will raise a StopIteration exception.

Example:


my_list = [1, 2, 3, 4, 5, 6]

#iterator object using iter() method

iterator_object = iter(my_list)

#iterate using next() method

#print(1)
print(next(iterator_object))

#print(2)
print(next(iterator_object))

#print(3)
print(next(iterator_object))

# next(obj) is same as obj.__next__()

#print(4)
print(iterator_object.__next__())

#print(5)
print(iterator_object.__next__())

# print(5)
print(iterator_object.__next__())

#raise Exception
print(iterator_object.__next__())

Output


1
2
3
4
5
6
Traceback (most recent call last):
  File "C:\Users\Vishvajit\Desktop\PF Article\Python Basic part1\test.py", line 30, in <module>
    print(iterator_object.__next__())
StopIteration

So, As you can see in the above example, How we have iterated through an iterator. Maybe, It is difficult for you but this is the process when you want to iterator an iterable using an iterator object.

The most elegant way to iterating it is by using Python for loop, You can iterator above iterable (list) with only two lines of code.

Let’s see how can we do that.

Example:


# list for iterating
my_list = [1, 2, 3, 4, 5, 6]
for i in my_list:
	print(i)

Output


1
2
3
4
5
6

Iteration

Iteration is nothing but the process of iterable and iterator is called iteration.

Building Custom Iterator

To create a custom Python iterator, you have to use just two Python magic methods __iter__() and __next()__.

The __iter__() method is going to be used for the returned iterator itself that is used to return a sequence of numbers.

And The __next__() is going to use to return the next item of the iterable.

The __next__() method in Python is used to return the next item of the iterable. At the end and subsequent call, it raises the StopIteration exception.

Let’s see an example of Python custom iterators. In this example, we are going to calculate the power of two for each item of the iteration.

Example: Create Custom Iterator Python


class CustomIterator:
    """ Class to implement power of 2 for each item of the iteration """
    
    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
            
            
             
# Create an object
obj = CustomIterator(5)

# Create iterator object
iterator = iter(obj)

# iterate each item using __next__() method

print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))

Output


1
2
4
8
16
32

You can also use Python for loop for iterator over a iterable class.

Example:


class CustomIterator:
    """ Class to implement power of 2 for each item of the iteration """
    
    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


          
# For loop for iterate iterable class
for i in CustomIterator(5):
	print(i)

StopIteration

When you execute the above program and used extra next(iterator), Then you will get a StopIteration exception but you can avoid this by using Python for loop.

Conclusion

So, in this article, we have seen all about Python custom iterators with the help of examples. This is one of the most important questions from the interview point of view because most of the interviewers ask this question to know your programming logic.

I hope you don’t have any confusion regarding the custom iterators in Python. If this article will help you, please keep visit and share this.

Reference:- Click Here

~ Thanks for reading

Type Conversion in Python
Python Property Decorator - @property

Related Posts