Introduction to Iterators in Python
The following article provides an outline for Iterators in Python. In python, an Iterator can be defined as an object for holding a set of values, which can be used in iteration operations in the program. For performing an iteration operation using the iterator object, the python had two special methods: iter () and next(). Python allows Iteration to be performed in both numbers and strings, where the data is represented as an iterator object. This functional method reduces redundancy and improves stability in the source code without increasing the length of the code.
newlist = ("soap", "knife", "handkerchief") newiter = iter(newlist) print(next(newiter)) #soap print(next(newiter)) #knife print(next(newiter)) #handkerchief
Strings in Python are also Iterable objects as we can get an iterator from it to traverse every character in it.
newstr = "apple" newiter = iter(newstr) print(next(newiter)) # a print(next(newiter)) # p print(next(newiter)) # p print(next(newiter)) # l print(next(newiter)) # e
How to Work with Iterators in Python?
Now, let’s dive into iterators:
1. Looping through an Iterator
Loop can be used to iterate through the iterable objects in python. Loops also use the same procedure as above, i.e. it creates an iterable object and keeps using the next method in each loop.
newlist = ("soap", "knife", "handkerchief") for a in newlist: print(a)
The basic advantage of for in loop or for each loop in python means less work than normal for loop in other languages.
newstr = "apple" for a in newstr: print(a)
2. Iterating an Iterable Object (List) using an Iterator
An iterable object is something from which we can get an iterator like some pre-built iterable object are – list, dict, string, tuple, etc.
# define a list mylist = [7,2, 5, 3] # retrieving an iterator using iter() myiter = iter(mylist) # iterate through it using next() print(next(myiter)) print(next(myiter)) ## next(object) is same as object.__next__() #print(my_iter.__next__()) #print(my_iter.__next__())
3. Creating an Iterator
To create an object or class as an iterator, we have to implement the iterator protocol methods __iter__() and __next__() to the object.
Both of these methods are needed to get the necessary help to make the object iterable.
- Iter – The iter method is always called on the initialization of an Iterator object. This method always returns an __iter__object and used to fetch iterable form any object.
- Next – The next method of an iterable will return the next values of the object. Whenever an iterator is used within a ‘for in’ loop, the next() method is implicitly called by the iterator object. To end the endless iteration in python, a stopiteration condition is also added in this method.
In the below example, we will create an iterator that will return odd numbers, starting from 1 like 1, 3, 5, and so on.
class OddSeries: def __iter__(x): x.a = 1 return x def __next__(x): i = x.a x.a += 2 return i newclass = OddSeries() newiter = iter(newclass) print(next(newiter)) # 1 print(next(newiter)) # 3 print(next(newiter)) # 5 print(next(newiter)) # 7 print(next(newiter)) # 9
The example stated above will continue as many times as we can print the next method with the object. If used inside a for loop, it would iterate infinitely without any break statement to stop the loop. To stop the iteration to go on forever, we have to use the StopIteration statement inside the Iterable object definition while creating it. The StopIteration statement should be written inside the __next__() method to add a termination condition to raise an error whenever the iteration crosses a specified number of iterations.
class OddSeries: def __iter__(x): x.a = 1 return x def __next__(x): if x.a <= 10: i = x.a x.a += 2 return i else: raise StopIteration newclass = OddSeries() newiter = iter(newclass) for j in newiter: print(j)
5. In-Built Iterators
The below program implies the use of iterator over inbuilt python entities like list, tuple, string, dictionary.
# A list value is been iterated print("Iteration over a list") l = [ " One " , " Two " , " Three " , " Four " , " Five " ] for iterator_element in l: print(iterator_element) # A tuple value is being iterated print("\n Iteration on a tuple ") t = ( " One " , " Two " , " Three " , " Four " , " Five " ) for iterator_element in t: print(iterator_element) # A string value is been iterated print("\n Iteration on a String") s = "Test" for iterator_element in s : print(iterator_element) # A dictionary value is been iterated print("\n Iteration on a dictionary element") d = dict() d[ '1234567890' ] = 1 d[ 'abcdefghij' ] = 2 for iterator_element in d : print("%s %d" %(iterator_element, d[iterator_element]))
- The program iterates across four different iterable objects such as list, tuple, string, and dictionary with the iterator “i”.
Understanding the Implementation of for-loop
As we have seen in the above example, that for-loop can iterate the list automatically.
Let’s see how the for-loop is implemented in Python:
for element in iterableObject: #do something with element
#create an iterator object from iterableObject iterObject = iter(iterableObject) while True: try: #retrieve the next element Element = next(iterObject) #do something with element except StopIteration: break
So technically, for-loop is creating an iterator object, iterObject, by calling iter() on the iterable object. For-Loop is the same as an infinite while-loop.
Inside the while-loop, it calls next()to retrieve the next element and then executes the body of for loop; after all the elements have been retrieved, then StopIteration is called, which internally ends the loop.
The below example is to create an iterator in Python and print the output pattern.
class PatternPrint: def __init__(x, mx = 10): x.mx = mx def __iter__(x): x.a = 1 return x def __next__(x): if x.a <= x.mx: i = x.a*'1' x.a += 1 return i else: raise StopIteration newiter = PatternPrint(12) for j in newiter: print(j)
Benefits of Python Loops
Given below are the benefits mentioned:
- Code reduction.
- Code redundancy is greatly resolved.
- Reduces code complexity.
- It brings in more stability into coding.
Iterators in Python are pretty useful stuff whenever we are dealing with any list, tuple, string, etc. It allows us to traverse through the entire components and helpful when the need is to be based on an entry in the array or character of a string, etc. Always we have to keep in my mind while declaring iterators that give the starting value of iteration, i.e. initialize it via iter, and the sequence logic should be given in the next method in order to print a sequence and also try giving StopIteration always since it resists your for loop to give an array out of bound error.
This is a guide to Iterators in Python. Here we discuss the basic concept of working with iterators in python through various examples and outputs. You may also have a look at the following articles to learn more –