Python Iterators
An iterator is an object that contains a countable number of values. With the help of iterator, we can traverse through all the values. Technically, in Python, an iterator is an object which implements the iterator protocol, which consists of methods __iter__() and __next__().
Iterator vs Iterable
Lists, Tuples, Dictionaries and Sets are all iterable objects. They are iterable containers which you can get an iterator form. All these objects have iter() method which is used to get an iterator.
Example
Return an iterator from tuple and print all the values
mytuple = ("apple", "banana", "strawberry") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit))
Output:
apple banana strawberry
Every strings are iterable objects, containing a sequence of characters
Example:
mystr = "apple" myit = iter(mystr) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit))
Output:
a p p l e
Looping through an
Iterator
We can also use for loop to iterate through an iterable objects. The for loop actually creates an iterator object and executes next() method for each loop.
Example:
mytuple = ("apple", "banana", "strawberry") myit = iter(mytuple) for x in mytuple: print(x)
Output:
apple banana strawberry
Create an iterator
To create an object/class as an iterator, we need to implement the methods __iter__() and __next__() to the object. The __iter__() function is similar to __init__() function, we can perform operations like initializations but must always return the iterator object itself. The __next__() method helps to return the next element in the sequence.
Example:
To create an iterator that return numbers, starting with 1 and each sequence increments by 1:
class Numbers: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 1 return x myclass = Numbers() myiter = iter(myclass) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter))
Output:
1 2 3 4
Stop Iteration
The example above would continue forever if we had use for loop. To prevent the iteration, we use the StopIteration statement.
Example:
In the next() method, we add a terminating condition to raise an error if iteration is done a specified number of times.
To stop after 20 iterations, we add the condition in for loop.
class Numbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x =self.a self.a += 1 return x else: raise StopIteration myclass = Numbers() myiter = iter(myclass) for x in myiter: print(x)