Python Iterator

Iterator is an alternative implementation for looping through and object. Iterator is an object that can give data  one at a time. 

Iterator and iterable

Iterable is any item that implements iterator protocol. List, dictionary, tuple, sets, strings, etc are iterable in python. Iterator is an object which implements two special methods __iter__() and __next__(). These two methods together are termed as iterator protocol. 

Why use iterator?

You have loops for going through item. Then why do we want to use iterator?  As the iterator gets item one at a time it is memory efficient. If you have large data (say data bigger than your RAM size ), then loading those data in RAM through list is not possible in those case you use iterator to get an object which can loop through data. Big data has a huge use case of iterator. And iterator are used everywhere in python such as in list, tuple, dictionary, etc.

Looping through a list

Let’s see how we loop through a list and then compare this to a solution from the iterator perspective. 

You can loop through a list using iter() and next() method.

list1 = [1, 2, 3, 4]
iterator = iter(list1)

print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))

Output:

1
2
3
4

If you try to get more data than there is in the list. You will get and StopIteration error.

Also you can loop through list using for loop like this:

list1 = [1, 2, 3, 4]

for item in list1:
    print(item)

Output:

1
2
3
4

Creating iterator

Iterator object can be creating by implementing two special methods , __iter__() and __next__(). Let’s see an example below

class MyIterator:
    def __iter__(self):
        self.item = 0
        return self

    def __next__(self):
        self.item += 1
        return self.item

c = MyIterator()
it = iter(c)
print(next(it))
print(next(it))
print(next(it))
print(next(it))

Output:

1
2
3
4

Above is a simple iterator, it has no way to stop it’s execution. If you want to run it through for loop you definitely want it to terminate after certain execution. Let’s implement StopExecution protocol and then run it using for loop.

class MyIterator:
    def __init__(self, mx):
        self.max = mx

    def __iter__(self):
        self.item = 0
        return self

    def __next__(self):
        if self.item < self.max:
            self.item += 1
        else:
            raise StopIteration

        return self.item

c = MyIterator(4)
iterator = iter(c)
for item in iterator:
    print(item)

Output:

1
2
3
4

Let’s see another example of getting cube of a number specific to certain point.

class MyCubeIterator:
    def __init__(self, mx):
        self.max = mx

    def __iter__(self):
        self.item = 0
        return self

    def __next__(self):
        if self.item < self.max:
            self.item += 1
            # you can also use math.pow(self.item, 3) like this
            # result = round(math.pow(self.item, 3))
            result = self.item * self.item * self.item
        else:
            raise StopIteration

        return result

c = MyCubeIterator(4)
iterator = iter(c)
for item in iterator:
    print(item)

Output:

1
8
27
64

Leave a Reply

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