Thursday, 23 September 2021

Python: Implement custom iterator

In this post, I am going to explain how to define custom iterator.

 

By defining both __iter__ and __next__ methods, you can make an object iterable. For example, let’s make OddNumbers class as iterbale by implementing __iter__, __next__ methods. Note here, you should throw ‘StopIteration’ from __next__ method when no elements left to iterate over.

class OddNumbers:

    def __init__(self, numbers_to_return):
        self.start = 1
        self.count = 0
        self.numbers_to_return = numbers_to_return

    def __iter__(self):
        return self

    def __iter__(self):
        return self

    def __next__(self):
        if self.count < self.numbers_to_return:
            self.count += 1
            temp = self.start
            self.start += 2
            return temp
        else:
            raise StopIteration

Iterate over OddNumbers object

my_iter = OddNumbers(5)

while True:
    try:
        nextEle = next(my_iter)
        print(nextEle)
    except StopIteration:
        break


Find the below working application.

 

custom_iterator.py

class OddNumbers:

    def __init__(self, numbers_to_return):
        self.start = 1
        self.count = 0
        self.numbers_to_return = numbers_to_return

    def __iter__(self):
        return self

    def __iter__(self):
        return self

    def __next__(self):
        if self.count < self.numbers_to_return:
            self.count += 1
            temp = self.start
            self.start += 2
            return temp
        else:
            raise StopIteration


my_iter = OddNumbers(5)

while True:
    try:
        nextEle = next(my_iter)
        print(nextEle)
    except StopIteration:
        break


Output

1
3
5
7
9


You can use for loop to iterate over an iterable in a better way.

for item in my_iter:
    print(item)


Find the below working application.

 

custom_iterator_2.py

class OddNumbers:

    def __init__(self, numbers_to_return):
        self.start = 1
        self.count = 0
        self.numbers_to_return = numbers_to_return

    def __iter__(self):
        return self

    def __iter__(self):
        return self

    def __next__(self):
        if self.count < self.numbers_to_return:
            self.count += 1
            temp = self.start
            self.start += 2
            return temp
        else:
            raise StopIteration


my_iter = OddNumbers(5)

for item in my_iter:
    print(item)


Output

1
3
5
7
9







 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment