Python Iterators

In Python, an iterator is an object that iterates over iterable objects such as lists, tuples, dicts, and sets. The iter() method is used to create the iterator object. It iterates using the next() method.

  • The iter() function (which in turn calls the __iter__() method) returns an iterator from them.
  • We use the next() function ( which in turn calls the  __next__() ) to manually iterate through all the items of an iterator.
  • When we reach the end and there is no more data to be returned, it will raise the StopIteration
Iterating with the “for” loop
li = [1,2,3,4]
for i in li:
    print(i)
Output:
1
2
3
4

In above example a list which is contain some numbers and print those numbers using simple for loop, now same thing we can do with iterators. Lets see in example:

Iterating with the python iterator
li = iter([1,2,3,4])
print("type of li-",type(li))
print(li)
type of li- <class 'list_iterator'>
<list_iterator object at 0x0000021F3F7BE3E0>

In above example create list using iter() and when we print list it will return a iterator object, from this object we can fetch element using next(). Lets see in example :

li = iter([1,2,3,4])
print(next(li))
print(next(li))
print(next(li))
print(next(li))
print(next(li))
Output :
1
2
3
4
Traceback (most recent call last):
  File "source/file/path", line 6, in <module>
    print(next(li))
StopIteration

In above example fetching element using next() when we call first time next() it will return a first value now again we will call next() it knows the last value of list which means it preserve the value of last stage ( or old value ) so it will give you next value but When we reach the end and there is no more data to be returned, it will raise the StopIteration. We can handle this exception using try-except block in python.

The another small example here to clear more about iterator:

li = iter([1,2,3,4])

print(next(li))
print(next(li))
for i in li:
    print(i)
Output :
1
2
3
4

In above example when we call next() twice it will preserve the last element of the list and after that when we call for loop it will start from where we leave it.

Building Custom Iterators

In Python, creating an iterator from scratch is simple. All we need to do now is implement the __iter__() and __next__() methods.

  • The iterator object is returned by the __iter__() method. Some initialization can be done if required.
  • The next item in the series must be returned using the __next__() method. It must raise StopIteration when it reaches the end of the call and in subsequent calls.

Here is the example in which we want to print numbers from 1 to 10.

class PrintNum():
    def  __init__(self):
        self.count = 1
    def __iter__(self):
        return self
    def __next__(self):
        if self.count <= 10:
            val = self.count
            self.count += 1
            return val
        else:
            raise StopIteration

obj = PrintNum()
for i in obj:
    print(i)
Output : 
1
2
3
4
5
6
7
8
9
10

In above example in __init__() we declare a count variable to count the step of printing number then we define a __iter__() it will return iterator object and the __next__() which will give you a next object and at the end we raise the exception which is StopIteration to stop this loop.

That is it for today, hope it helps.
If you have any suggestion for this article please make a comment in comment section below.

If you like this article, you can buy me a coffee. Thanks!

Python Iterators

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top