Python - Iterators
There are various iterable objects in Python like lists, tuples, sets, dictionaries, and strings, etc. These iterables can get iterator form which means that an iterator can be iterated upon and each elements of the iterator can be accessed using a loop statement. In Python, an iterator object must implement following methods:
- __iter__(): to initialize an iterator.
- __next__(): to perform operations for next element and return next element of the iterator.
Example:
In the example below, an iterator called MyIter is created from the iterable called MyList and after that next() method is used to access next element of the iterator. Please note that, a StopIteration exception is raised when the iterator do not have more elements to iterate upon.
MyList = ['MON', 'TUE', 'WED'] MyIter = iter(MyList) print(next(MyIter)) print(next(MyIter)) print(next(MyIter))
The output of the above code will be:
MON TUE WED
Loop over an Iterator
The for loop can also be used with any iterable to iterate over the elements of it.
Example:
In the example below, a for loop is used to iterate over the iterable called MyList.
MyList = ['MON', 'TUE', 'WED'] for i in MyList: print(i)
The output of the above code will be:
MON TUE WED
Create an Iterator
A user-defined iterator can be created in Python and it is must to define __iter__() and __next__() methods while creating it. The __iter__() method is used to initialize the iterable object or class and the __next__() method is used to perform some operation to return next element of the sequence.
Example:
In the example below, an iterator called MyIterClass is created which initiates with square of 1. The next element of this iterator is the square of the next natural number.
class MyIterClass: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 1 y = x * x return y IterObj = MyIterClass() MyIter = iter(IterObj) for i in range(1, 11): print(next(MyIter), end=" ")
The output of the above code will be:
1 4 9 16 25 36 49 64 81 100
StopIteration
The StopIteration statement can be used to stop iteration at desired point. In the __next__() method, a terminating condition can be created to raise StopIteration error. See the example below:
Example:
In the example below, the iterator raises StopIteration exception after reaching square of 5.
class MyIterClass: def __iter__(self): self.a = 1 return self def __next__(self): if self.a < 6: x = self.a self.a += 1 y = x * x return y else: raise StopIteration IterObj = MyIterClass() MyIter = iter(IterObj) for i in range(1, 11): print(next(MyIter))
The output of the above code will be:
1 4 9 16 25 Traceback (most recent call last): File "Main.py", line 19, in <module> print(next(MyIter)) File "Main.py", line 13, in __next__ raise StopIteration StopIteration