Skip to content Skip to sidebar Skip to footer

Need To Implement The Python Itertools Function "chain" In A Class

I am trying to emulate the 'chain' function in itertools in python. I came up with the following generator. # Chain make an iterator that returns elements from the first iterable

Solution 1:

There is not (much) difference between def chain_for(*a): and def __init__(self, *a):. Hence, a very crude way to implement this can be:

class chain_for:
    def __init__(self, *lists):
        self.lists = iter(lists)
        self.c = iter(next(self.lists))

    def __iter__(self):
        while True:
            try:
                yield next(self.c)
            except StopIteration:
                try:
                    self.c = iter(next(self.lists))
                except StopIteration:
                    break
                yield next(self.c)

chain = chain_for([1, 2], [3], [4, 5, 6])
print(list(chain))

Outputs:

[1, 2, 3, 4, 5, 6]

Post a Comment for "Need To Implement The Python Itertools Function "chain" In A Class"