Learn Python Programming

Python Iterators


Iterators in Python is an object which allows programmer to traverse through all the elements of a collection like list, tuple, dictionary, etc.

Iterators are present everywhere in Python. They are mostly implemented within the for loops, comprehensions, generators etc. but are hidden in plain sight.

Iterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time.

Iterator protocol consists of two methods: __iter__() and next().

  • Cleaner code.
  • Iterators can work with infinite sequence.
  • Iterators save resources.

Let us understand with an example:

my_list = [1,2,3,4,5]
for i in my_list:
    print(i)

#OUTPUT
1
2
3
4
5

Here, in the above example, you see output iterating one by one. So, here i is called iterator and my_list is iterable.

Iterator vs Iterable

Lists, tuples, dictionaries and sets are all iterable objects. All these objects have a iter() method which is used to get an iterator. Also strings are iterable objects.

my_tuple = ("Python", "Php", "Java")
my_it = iter(my_tuple )

print(next(my_it))
print(next(my_it))
print(next(my_it))

#OUTPUT
Python
Php 
Java
my_str  = "python"
my_it   = iter(my_str)

print(next(my_it))
print(next(my_it))
print(next(my_it))
print(next(my_it))
print(next(my_it))
print(next(my_it))
print(next(my_it))
print(next(my_it))

#OUTPUT
p
y
t
h
o
n
Traceback (most recent call last):
  File "iterator_ex.py", line 22, in <module>
    print(next(my_it))
StopIteration

Here, in the above example, you also need to care about the the stopIteration error. You can use try catch block to handle stopIteration error.

my_str  = "python"
my_it   = iter(my_str)
try:
    print(next(my_it))
    print(next(my_it))
    print(next(my_it))
    print(next(my_it))
    print(next(my_it))
    print(next(my_it))
    print(next(my_it))
    print(next(my_it))
except StopIteration as ex:
    print("Iteration stopped!")


#OUTPUT
p
y
t
h
o
n
Iteration stopped!

Creating your own Iterator

To create an object/class as an iterator you need to implement the special methods __iter__() and __next__() in your object.

The __iter__() method returns the iterator object itself that goes through the each element of the given object.

The __next__() allows you to implement some operation, where you can write code to return next item in the sequence.

class myIterClass:
    def __init__(self):
        pass
    def __iter__(self):
        self.count = 1
        return self
    def __next__(self):
        count = self.count
        self.count += 1
        return count

obj = myIterClass()
itr = iter(obj)

print(itr.__next__())
print(itr.__next__())
print(itr.__next__())
print(itr.__next__())
print(itr.__next__())

#OUTPUT
1
2
3
4
5

To prevent the iteration to go on forever, you can use the StopIteration statement. In the next() method, you can add a terminating condition to raise an error if the iteration is done a specified number of times:

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

obj = myIterClass()
itr = iter(obj)

for i in itr:
    print(i)

#OUTPUT
1
2
3
4
5
6
7
8
9
10