Iterators in Python
Introduction
In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values.
The iterator is utilized to iterate on the iterable objects such as lists, tuples, dicts, and sets. It contains two methods which is __iter__(iterable) method and __next__() method.
The iter() method is used for initializing the iterator object and the next() method is used for iteration.
Iterable
The iterable is refer to an object like lists, tuples, dictionaries, and sets. These all are iterable objects and creates an iterator when crossed to the iter() method. The iterable returns an iterator.
Example of Python inbuilt iterator:
iterable_value = 'Tutorial'
iterable_obj = iter(iterable_value)
while True:
try:
# Iterate by calling next
item = next(iterable_obj)
print(item)
except StopIteration:
# exception will happen after iteration is completed
break
Output:
T
U
T
O
R
I
A
L
Explanation: In the above example, we have defined the use of Python inbuit iterator. We have created an iterator with iter() method.
Example of Iterator with a tuple:
mytuple = ("mango", "raspberry", "lemon")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Output:
mango
raspberry
lemon
Explanation: In the above example, we have defined the iterator by using a tuple. Here, we have used the iter() method with a tuple and printed the result.
Example of Iterator with a String:
mystr = "pineapple"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Output:
p
i
n
e
a
p
p
l
e
Explanation: In the above example, we have defined the iterator by using a string of character. Here, we have used the iter() method with a string and printed the result.
Creating an Iterator
As we all know that the init() function is carried by all classes. When the object is created it allows initialization of the object.
The iter() method works the same as an iterator, we can do initialization, but an iterator object is returned itself always.
Also, the next() method enables us to do initialization, and the next item must be returned.
Let's take an example here the custom iterator can return an even number 1 each time the iteration is done.
Example 1:
class Evenit:
def __init__(self, max=0):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n <= self.max:
if self.n % 2 ==0:
result=self.n
self.n += 1
return result
else:
self.n += 1
return 1
else:
raise StopIteration
# create an object
numbers = Evenit(10)
for i in numbers:
print(i)
Output:
0
1
2
1
4
1
6
1
8
1
10
Example 2:
class Test:
# Constructor
def __init__(self, limit):
self.limit = limit
# iterator object will creates
def __iter__(self):
self.x = 10
return self
def __next__(self):
# Storing the current value
x = self.x
# Stopping iteration
if x > self.limit:
raise StopIteration
self.x = x + 1;
return x
# from 10 to 15 numbers will printing
for i in Test(15):
print(i)
# Prints none
for i in Test(5):
print(i)
Output:
10
11
12
13
14
15
Explanation: In the above examples 1 and 2, we have created an iterator. Here, we have done intiliazation with next() method and returned next item. The custom iterator returned an even number 1 each time the iteration is done.
StopIteration
The stopiteration statement is used for stopping the iteration to go on endlessly. It is supposed an Exception and it can be handled easily by picking that exception like other exceptions in Python.
The method next() or __next__() raises the exception for stopping the iterations or it shows that there are no more elements are left for iteration.
Example:
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 18:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Explanation: In the above example, we have defined the use of stopiteration method. Here we have used the method next() or __next__() that raises the exception for stopping the iterations.
Containers
The containers can be defined as the objects that hold the values of data. We can check that the value is located in the container.
Containers are iterables i.e, lists, dictionaries, sets, strings, and tuples.
Example:
if 1 in [1,6,2]:
print('This is a List')
if 7 not in {4,1,8}:
print('This is a Tuple')
if 'apple' in 'pineapple':
print('This is a String')
Output:
This is a List
This is a Tuple
This is a String
Explanation: In the above examples, we have checked that the value is located in the container or not by using the conditional statements.
Generators
Generators are defined as the way or method of generating iterators.
In simple words, a generator is referred to the function that returns an iterator that we can iterate upon.
In Python, it is very easy to create a generator and it uses the yield statement instead of the return statement.
Example:
def series_generator(low, high):
while low <= high:
yield low
low += 1
n_list = []
for num in series_generator(4,16):
n_list.append(num)
print(n_list)
Output:
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
Explanation: In the above example, generators is defined. As we can see that it returned an iterator on which we can iterate upon. Here we have used the yield statement instead of return statement.
Conclusion
In the above article, you have learned about the iterators in Python and also we have seen some more methods like generators and containers. And we learned how to implement them.