Good day learners! In our previous tutorial, we learned about Python Operator Overloading. In this tutorial we are going to learn about Python Iterator.
Table of Contents
Knowingly or unknowingly, you have used iterator in your Python code. Basically, an iterator is an object which is used to iterate through an iterable element. Didn’t understand the meaning of the last line? Well, don’t worry. We will make you understand about Python Iterator through our tutorial.
Python Iterator and Iterable Elements
Most of the objects of Python are iterable. In python, all the sequences like Python String, Python List, Python Dictionary etc are iterable. Now, what is iterator? Suppose, A group of 5 boys are standing in a line. Your are pointing at the first boy and ask him about his name. Then, he replied. After that, you ask the next boy and so on. The below picture will illustrate the thing.
In this case, you are the Iterator!!!! Obviously, the group of boys is the iterable element. Hope you understand now.
Python Iterator Protocol
Python Iterator Protocol includes two functions. One is
iter() and the other is
next(). In this section, we will learn to how to traverse an iterable element using Python Iterator Protocol.
In the previous section, we gave the example of group of 5 boys and you. You are the iterator and the boys group is the iterable element. After knowing the name of one boy, you ask the same question to the next boy.
After that, you do it again. iter() function is used to create an iterator of an iterable element. And the next() function is used to iterate to the next element.
Python Iterator Example
If the iterator go beyond the number of iterable elements then the next() method will raise
StopIteration exception. See the code below for python iterator example.
Copylist_string = ['Boy 1', 'Boy 2', 'Boy 3', 'Boy 4', 'Boy 5'] iterator_you = iter(list_string) # point the first boy output = next(iterator_you) # This will print 'Boy 1' print(output) # point the next boy, the second boy output = next(iterator_you) # This will print 'Boy 2' print(output) # point the next boy, the third boy output = next(iterator_you) # This will print 'Boy 3' print(output) # point the next boy, the fourth boy output = next(iterator_you) # This will print 'Boy 4' print(output) # point the next boy, the fifth boy output = next(iterator_you) # This will print 'Boy 5' print(output) # point the next boy, but there is no boy left # so raise 'StopIteration' exception output = next(iterator_you) # This print will not execute print(output)
CopyBoy 1 Boy 2 Boy 3 Boy 4 Boy 5 Traceback (most recent call last): File "/home/imtiaz/Desktop/py_iterator.py", line 32, in output = next(iterator_you) StopIteration
Making of a Python Iterator
However, you can make your own specified Python Iterators. To do so, you have to implement a Python class. I assume that you know about Python Class. If you don’t know about this, you can read our tutorial about Python Class.
As we have said earlier that, Python Iterator Protocol consist of two methods. So we need to implement those method.
For example, you want to generate a list of fibonacci number so that each time call the next function it returns you the next fibonacci number.
To raise the exception, we limit the value of n below 10. If the value of n reach 10, it will raise an exception. The code will be like this.
Copyclass fibo: def __init__(self): # default constructor self.prev = 0 self.cur = 1 self.n = 1 def __iter__(self): # define the iter() function return self def __next__(self): # define the next() function if self.n < 10: # Limit to 10 # calculate fibonacci result = self.prev + self.cur self.prev = self.cur self.cur = result self.n += 1 return result else: raise StopIteration # raise exception # init the iterator iterator = iter(fibo()) # Try to print infinite time until it gets an exception while True: # print the value of next fibonacci up to 10th fibonacci try: print(next(iterator)) except StopIteration: print('First 9 fibonacci numbers have been printed already.') break # break the loop
So, the output will be
Copy1 2 3 5 8 13 21 34 55 First 9 fibonacci numbers have been printed already.
Why Making Python Iterator
After going through the previous section, a question may arise to your mind that why should we make Python Iterator.
Well, we have seen already that iterator can traverse an iterable element. Suppose, in our previous example if we make a list of fibonacci numbers and then traverse it via a Python Iterator, it would take huge memory. But if you create a simple Python Iterator class, you can serve your purpose without consuming that much memory.
So that’s all for Python Iterator. Hope that you are now able to work with Python Iterator. For any further query, you can use the comment box. Learn and practice as much as you can.
Reference: Python Doc