Python Iterators
An iterator is an object containing a number of countable values.
An iterator is an object to which iteration is possible, meaning all the values can be crossed.
In Python, an iterator is an art object that implements a protocol to the iterator that consists of the __iter__()
and __next__
methods.
Iterator vs Iterable
Lists, tuples, dictionaries and sets are all objects which can be iterated. You can get an iterator from them are iterable containers.
The iter()
method is used to retrieve an iterator from any objects :
Example 1 :- Return a tuple iterator and print out each value :
mytuple = ("aa", "bb", "cc")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Output :-
bb
cc
Strings are also can work with iterable objects.
Example 2 :- Make a string iterable objects and print each character one by one :
mystr = "Hi"
myit = iter(mystr)
print(next(myit))
print(next(myit))
Output :-
i
Looping Through an Iterator
A for
loop can also be used to iterate via an iterable object :
Example 1 :- Iterate the values of a tuple :
mytuple = ("aa", "bb", "cc")
for x in mytuple:
print(x)
Output :-
bb
cc
Example 2 :- Iterate the characters of a string :
mystr = "Hi"
for x in mystr:
print(x)
Output :-
i
The for
loop generates an iterator object and executes for each loop the next()
method.
Related Links
Create an Iterator
You have to implement __iter__()
and __next__()
methods into your object in order to generate an object/class as the iterator.
As you know, in the Python Classes/Objects chapter, all classes contain __init__()
function that lets you initialise when creating the object.
The __iter__()
method works similar, operations may be performed (initialising etc.), but the object iterator must always be returned.
You can also use the __next__()
method and have to return the next item in the series.
Example :- Create an iterator which return numbers from 1 and increases each series by one sequence (returns 1,2,3 etc.) :
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
Output :-
2
3
StopIteration
If you have enough next()
statement or were using it in a loop, the preceding example would run for
loop.
We can use the StopIteration
statement to prevent this iteration from going forever.
In the method __next__()
termination condition can be added to make an error when the iteration is made several times :
Example :- Stop after 5 iterations
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 5:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
Output :-
2
3
4
5
Related Links