The list, tuples and dictionary in python are iterators. It means, we can iterate over it ie we can run a for loop on it to get its values. These are the default build-in iterators in python.
We can create our own iterators too. Here we will learn to create our very own iterators and iterate over it.
How to create a iterators:
Technically the objects that will implement the method __iter__ and __next__ are iterators. So we need to create a class and make it implement the two methods. Bellow we have a simple example of iterators, where you can find the method being implemented by the class.
Creating our own simple iterators in python3
# trying to create iterators like list , tuples class MyIterators: def __init__(self, maxpoint): self.max = maxpoint #called when the iteration is called #pint from which iteration start def __iter__(self): self.item = 0 return self #to move to the next element #until it stops do some action and return def __next__(self): item = self.item if item > self.max: raise StopIteration self.item = item +2 return item n=MyIterators(10) for item in n: print(item)
Iterating through iterable :
One way will be to use the for loop as in the example above. But we can also make use ot iter method and get the next value as shown bellow
n = MyIterators(2) item = iter(n) #using the iter method as its iterable print(next(item)) #getting next item with next method print(next(item))
Using the StopIteration to stop the iteration:
As seen in the iterator example above to stop the iteration from running forever. We use the StopIteration to raise the exception. Which will stop the process when the max limit is reached.