Python Iterators: Python Iterator is an object that contains a countable no.of values. In python, an iterator is an object which implements iterator protocol, consisting of methods _iter_ ( ) and _next_( ). An object is iterable if we can get them from it. Most of the built-in containers in Python like tuple, strings, etc. are iterable.
__iter__ ( )
It is called on the initialization of an iterator. This should return an object that has a next or __next__ ( )
__next__ ( )
The iterator next method should return the next value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object. This method should raise a StopIteration to signal the end of the iteration.
Python Iterators
Iterator VS Iterable
Lists, Tuples, dictionaries, and sets all are iterable objects. All these methods have an iter( ) which is used to get an iterator.
Example
mytuple=("Redmi","Vivo","Oppo") myit=iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit))
Output
Redmi
Vivo
Oppo
Strings are also iterable objects and can return an iterator.
Example
mystr = "India" myit = iter(mystr) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit))
Output
I
n
d
i
a
Looping through iterator
Looping through iterator
Example
mytuple=("vivo","oppo","Redmi") for x in mytuple: print(x)
Output
vivo
oppo
Redmi
Python Infinite Iterators
The built-in function iter() can be called with two arguments where the first argument must be a callable object (function) and second is the sentinel. And the iterator calls this function until the returned value is equal to the Sentinel. We can also build our own infinite iterators.
Example
class InfIter: """Infinite iterator to return all odd numbers""" def __iter__(self): self.num = 1 return self def __next__(self): num = self.num self.num += 2 return num
Output
>>> a = iter(InfIter())
>>> next(a)
1
>>> next(a)
3
>>> next(a)
5
>>> next(a)
7