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:
In the below example, 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))
MON TUE WED
The for loop can also be used with any iterable to iterate over the elements of it.
In the below example, a for loop is used to iterate over the iterable called MyList.
MyList = ['MON', 'TUE', 'WED'] for i in MyList: print(i)
MON TUE WED
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.
In the below example, 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=" ")
1 4 9 16 25 36 49 64 81 100
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. Please see the example below:
In the below example, 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))
1 4 9 16 25 Error! StopIteration