Generally, iterators are used to iterate over a list of objects. We use iterators without knowing we are using it. Let’s understand Iterators in python and look at the below example
a = [1,2,4,5,6,7,8]
for i in a:
print(i)
Here we have used iterator behind the scenes of for-in
to loop over a list.
How to create Iterators?
Iterators consist of two important functions
__iter__
__next__
Note: In python 2.7 it was next function in 3.x is it __next__
If your class has these two functions written properly it can be used as an iterator and can be used with for-in
.
Iterator Visualization
Let’s take a list and try to iterate over it with an iterator.
a = [1,2,3,4,5,6,7] it = iter(a) #same as it = a.__iter__() print(it.__next__())
Every time you print it will print the next value in the list till it reaches stop iteration exception. Now let’s try and create iterator classes.
Basic Iterator Example.
class Iterator: def __init__(self, value): self.value = value def __iter__(self): return self def __next__(self): return self.value a = Iterator("asdad") for item in a: print(item)
Here what we are doing is creating an object of Iterator class which has iter which returns itself and next which returns the values. This is then used in for-in
to demonstrate iterator working.
This iterator will keep on printing whatever value you will provide it forever. It will not break. Since in __next__
function we are just returning the value itself and not changing anything else. Ideally, it should change some value which defines when this iterator will stop.
Let us now try and write an iterator which will loop over our list of numbers and print it.
Creating List iterators
class RepeaterNumber:
def init(self, value):
self.value = value
self.index = 0
self.length = len(value)
def __iter__(self):
return self
def __next__(self):
if self.index<self.length:
returnvalue = self.value[self.index]
self.index = self.index + 1
return returnvalue
else:
raise StopIteration
As you can see now in __next__
the function we are checking if we reached will the end of the len
or not if yes we are stopping the iteration.
This is how iterator for the list may be implemented.
This will directly work with for-in
keyword. Lets see how for-in
must have been implemented behind the scenes.
it = RepeaterNumber([1,2,3,4,5,6,7,8])
while True:
try:
return it.__next__()
except StopIteration as e:
break
This is how it has been working. You can have a look at the implementation for lists in python.
Now let’s try and see if manually getting an iterator will work with our class?
a=[1,2,3,4,5,6,7,8,9] a=RepeaterNumber(a) it = a.__iter__() print(it.__next__()) print(it.__next__()) print(it.__next__())
If it works we have learned the basic of how iterator works. Iterate if you still have problems. 🙂
Read more in python here.
If you like the article please share and subscribe.