Program to illustrate the use of iterator in Python
In this tutorial, let’s see how iterators are implemented in Python. Python allows programmers to create their own custom iterators. For this, you simply have to implement the _iter_() and _next_() methods in your class.
A program that creates an iterator to print squares of numbers:
class Square: def__init__(self): self.val=0 def__iter__(self): return self def__next__(self): self.val +=1 return self.val ** 2 Sq = Square() count = 0 for num in Sq: print(num, end=" ") if count == 10: break count += 1
OUTPUT: 1 4 9 16 25 36 49 64 81 100 121
The __iter__() method returns the iterator object itself. You can also use the for loop to traverse through the list using the iter(). The __next__() method checks the indexes against the length specified. The method, otherwise, extracts the numbers at the index and squares them, and returns the number. For Python 3.x versions, the __iter__() and __next__() methods are implemented while for versions below Python 3, the iter() and next() are used.
The __init__() method has a special significance in Python classes. The __init__() method is automatically executed when the object of a class is created. The method is used to initialize the variables of the class object. Then we have an object variable that is unique for every object. When an object is created and the __init__() method is called, the object variable is initialized. The object variable belongs to only a particular object.
Advantages of using iterator:
- We can implement a cleaner code.
- Iterators can work with infinite sequences.
- Resources efficiently used.
Leave a Reply