Python Iterator and creating our own iterators

Posted on Aug. 4, 2019
python
iterator
1035

In this article we are going to know more about Python iterators and how to create our own iterators in Python.

What is an iterator

An iterator is an object that produces a series of values for iteration. More precisely if i is an iterator then for each call to next(i) will produces an element and raise StopIteration exception when all series elements are iterated.

So lets see the below example

n_list = [1,2,3,4,5]
n_iterator = iter(n_list)

print(next(n_iterator))
# 1
print(next(n_iterator))
# 2
print(next(n_iterator))
# 3
print(next(n_iterator))
# 4
print(next(n_iterator))
# 5
print(next(n_iterator))
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# StopIteration

We can also n_iterator.__next__() to get next element from the iterator.

We can also use for loop to get elements from iterator and it will manages the StopIteration exception.

n_list = [1,2,3,4,5]
n_iterator = iter(n_list)

for n in n_iterator:
    print(n)

# prints
# 1
# 2
# 3
# 4
# 5

 

So here list [1,2,3,4,5] is an iterable object that produces an iterator using iter([1,2,3,4,5]).

 

Creating our own iterator

Now we are trying to create our own iterator, for that we have to implement built in methods __iter__ and __next__. Below is the example of even number generator within the range (1,n).

class EvenIterator:
    def __init__(self, n = 0):
        self.n = n

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

    def __next__(self):
        self.item += 2
        if self.item <= self.n:
            return self.item
        else:
            raise StopIteration

a = EvenIterator(9)
for i in iter(a):
    print(i)

# prints
# 2
# 4
# 6
# 8

 

Uses of Iterator.

One can have as many as iterators they need with same iterable object and also maintaining its own state of progress.

Through Iterators we can produces infinite series.

Iterators also saves system resources by saving only one element in the memory at a time.

 

 

If you found any other uses of iterators please comment below and also share some of your interesting iterator implementations.

 




0 comments

Please log in to leave a comment.