[Solved] Need to implement the Python itertools function “chain” in a class


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]

6

solved Need to implement the Python itertools function “chain” in a class