Python Certification Training for Data Scienc ...
- 48k Enrolled Learners
- Live Class
Hey, this blog will cover the most favorite topic of the programmers and coders i.e. Iterators in Python. We will be doing an in-depth study on the iterators and how they work in Python programming language. Stay with us till the end.
What is iterator in Python?
A python iterator is a container containing a countable number of values. Values in a container can be traversed using Iterators (Particularly lists).
Apart from traversal, Iterators also gives access to data elements in a container but does not itself perform iteration (i.e., not without some significant liberty taken with that concept or with trivial use of the terminology. An iterator is almost similar to a database cursor in behavior.
Iterator in Python
Iterator is any type of Python that can be used with a ‘for in loop’.
Any object that is to be used as an iterator must implement the following methods.
1. __iter__ method.
It is called on initialization of an iterator.
It should return an object that has a next or __next__ method.
2. next. The iterator next method returns the next value for the iterable.
When an iterator is used with a ‘for in’ loop, next() is implicitly called by for loop on the iterator object. This method should use a StopIteration to signal the end of the iteration.
Together these two methods are called Iterator Protocol.
Below is a simple Python program that creates iterator type to iterate from 10 to given limit. For example, if limit is 17, then it prints 10 11 12 13 14 15 16 17. And if limit is 8, then it prints nothing.
Take a look at the below example demonstrating the working of iterators that iterates from 10 to given value.
# An iterable user defined type class Test: # Cosntructor def __init__(self, limit): self.limit = limit # Called when iteration is initialized def __iter__(self): self.x = 10 return self # To move to next element. In Python 3, # we should replace next with __next__ def next(self): # Store current value ofx x = self.x # Stop iteration if limit is reached if x > self.limit: raise StopIteration # Else increment and return old value self.x = x + 1; return x # Prints numbers from 10 to 15 for i in Test(15): print(i) # Prints nothing for i in Test(5): print(i)
Run an iterator from a tuple and print each value:
mytuple = ("apple", "banana", "cherry") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit))
C:UsersMy Name>python demo_iterator.py
Strings are also iterable objects, and can return an iterator:
Strings are iterable objects which contain a sequence of characters
mystr = "banana" myit = iter(mystr) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit))
C:UsersMy Name>python demo_iterator2.py
For loop to iterate through an iterable object
Using the ‘for’ loop is a more elegant way of automatically Iterating values.
mytuple = ("apple", "banana", "cherry") for x in mytuple: print(x)
C:UsersMy Name>python demo_iterator_loop.py
Now, Let’s see how to iterate characters of a String using FOR loop
mystr = "banana" for x in mystr: print(x)
C:UsersMy Name>python demo_iterator_loop2.py
In this section, we will be knowing about an important feature of Iterators i.e. StopIteration
To understand what it means we will first go through a code.
Here we create an iterator that returns numbers, starting from 1, and each sequence will increase by one (returning 1,2,3,4,5 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)) print(next(myiter)) print(next(myiter))
The example above would continue forever if we had unlimited next() statements, or if it was used with a for loop.
To prevent this iteration to go on forever, we use the StopIteration statement. In the __next__() method, we add a terminating condition to raise an error if the iteration is done a specified number of times (which is 20 in the below example)
class MyNumbers: 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 = MyNumbers() myiter = iter(myclass) for x in myiter: print(x)
It is not always mandatory that the item in an iterator object has to exhaust. There can be infinite iterators (which never ends). Here is a basic example to demonstrate infinite iterators.
The built-in function iter() can be called with two arguments where the first argument must be an object (function) that can be called and second is the sentinel. The iterator calls this function until the returned value becomes equal to the sentinel.
>> inf = iter(int,1)
We can see that the int() function always returns 0. So passing as iter(int,1), it will return an iterator that keeps calling int() until the returned value equals 1. This never happens and thus, we get an infinite iterator. We must be careful when handling such iterator.
This is all about Iterators in Python. Considering the usage of Iterators, it’s very important to learn about these and how to implement it in an effective way. Since you have reached this far, you might now be in a position to make Iterators of your own.
To get in-depth knowledge on Python along with its various applications, you can enroll for live Python Certification Training with 24/7 support and lifetime access.
Thanks for reading, I hope it helped. Keep Learning.