Python - Iterators
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().
Lists, tuples ,sets and dictionaries are all iterable objects. They are iterable containers which you can get an iterator from.
All these objects have a iter() method which is used to get an iterator:
Return an iterator from a tuple, and print each value:
tuple=("Laptop","Computer","Tab")
i= iter(tuple)
print(next(i))
print(next(i))
print(next(i))
====o/p=====
Laptop
Computer
Tab
Even strings are iterable objects, and can return an iterator:
Strings are also iterable objects, containing a sequence of characters :
string = "water melon"
i=iter(string)
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))
======O/P======
w
a
t
e
r
m
e
l
o
n
We can also use a for loop to iterate through an iterable object :
Iterate the values of a tuple:
tuple=("CSE","ECE","EEE","IT","MECH","CIVIL")
for i in tuple:
print(i)
=======O/P=======
CSE
ECE
EEE
IT
MECH
CIVIL
Iterate the characters of a string :
string="CIVIL"
for i in string:
print(i)
=====o/p=====
C
I
V
I
L
To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object.
As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__(), which allows you do some initializing when the object is being created.
The __iter__() method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself.
The __next__() method also allows you to do operations, and must return the next item in the sequence.
Create an iterator that returns numbers, starting with 100, and each sequence will increase by one (returning 100,200,300,400,500 etc.):
class MyNumbers:
def __iter__(self):
self.a = 100
return self
def __next__(self):
x = self.a
self.a += 100
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
======o/p=====
100
200
300
400
500
The example above would continue forever if you had enough next() statements, or if it was used in a for loop.
To prevent the iteration to go on forever, we can use the StopIteration statement.
In the __next__() method, we can add a terminating condition to raise an error if the iteration is done a specified number of times.
stop after 20 iterations :
class MyNumbers:
def __iter__(self):
self.a = 100
return self
def __next__(self):
if self.a <= 2000:
x = self.a
self.a += 100
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
=======O/P========
100
200
300
400
500
600
700
800
900
1000
1100
1200
1300
1400
1500
1600
1700
1800
1900
2000