Iterator pattern return infinite objects

Question:

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

1
2
3
4
5

But instead I get

12345
12345
12345
....

How can I solve this?

Thanks

Asked By: Tlaloc-ES

||

Answers:

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
Answered By: Riccardo Bucco
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.