Thursday, May 14, 2020

Python - How does an iterator work



 In this article, we will discuss how does an iterator work.  Python has 2 function related to iterator: iter and next. iter creates an iteration object for the requested input, and the next function returns the next element present in the iterator. next keeps on returning till the last element is reached.

   Let us create an iterator for a list and see how the next and iter function works:
>>> l1 = [2,25,33,12]
>>> l1
[2, 25, 33, 12]
>>> it1 = iter(l1)
>>> it1
<list_iterator object at 0x7fc24f93aa58>
>>> next(it1)
2
>>> next(it1)
25
>>> next(it1)
33
>>> next(it1)
12
>>> next(it1)
Traceback (most recent call last):
  File "", line 1, in 
StopIteration
>>> 
When we printed it1, it shows it as an list_iterator object. Everytime next is hit, it gave the next element and finally when there are no more elements, it gives StopIteration.

When we hit iter, it actually calls __iter__ method of the corresponding class. Meaning when we call iter on a list, it will call __iter__ of the list class.  Similarly, when we hit next on an object, it calls the __next__ of the corresponding object.

   Let us write a test class and have __iter__ and __next__ methods:  This class takes a list as input and assigns it to data variable. The __iter__method simply returns the reference. The __next__ method returns the next available data element and increments the index by 1 after every iteration. And on finally reaching the maximum, the StopIteration exception is thrown.

Let us run and check:
>>> from iterator import TestIterator
>>> t1 = TestIterator([2, 25, 33])
>>> t1
<iterator.TestIterator object at 0x7f5782d4ea90>
>>> next(t1)
2
>>> next(t1)
25
>>> next(t1)
33
>>> next(t1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/guru/iterator.py", line 13, in __next__
    raise StopIteration()
StopIteration
>>> 
  When the object t1 is created, it is showing as iterator.TestIterator object. On subsequent calls to next function, the __next__ method gets called and we get the subsequent values. Its this simple to have our own iterator.
>>> t1 = TestIterator([2, 25, 33])
>>> t2 = iter(t1)
Iter got called
>>> t2
<iterator.TestIterator object at 0x7f5782d4ec88>
>>> 
  As seen here, on calling iter, the __iter__ method got called.

No comments:

Post a Comment