Python Iterators
Python Iterators
Iterators in python are used to iterate over iterable objects or container datatypes like lists, tuples, dictionaries, sets, etc.
It consists of __iter__() and __next__() methods.
__iter__() : to initialize an iterator, use the __iter__() method.
__next__() : This method returns the next item of the sequence.
Using inbuilt iterators:
Output:
Creating Custom iterators:
Output:
In both the above examples, we can see that there is an StopIteration statement inside the except block. This is to prevent the iteration from continuing forever.