Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterator pattern return infinite objects

Hello I am trying to build a class list based like this

class DummyList(Iterator):
    ...
    def __next__(self) -> int:
        list = [1, 2, 3, 4, 5]
        for i in list:
            yield i

And I am using like this

dl = DummyList()

for i in dl:
    print(i)

The output that I expected was

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1
2
3
4
5

But instead I get

12345
12345
12345
....

How can I solve this?

Thanks

>Solution :

This would be the correct way to implement an iterator:

from collections.abc import Iterator


class DummyList(Iterator):
    def __init__(self):
        self.lst = [1, 2, 3, 4, 5]
        self.current = -1

    def __iter__(self):
        return self

    def __next__(self):
        self.current += 1
        if self.current < len(self.lst):
            return self.lst[self.current]
        raise StopIteration

This is the output:

dl = DummyList()

for i in dl:
    print(i)
1
2
3
4
5
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading