Search code examples
pythonclasspython-itertoolschain

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
# until it is exhausted, then proceeds to the next iterable, until all
# of the iterables are exhausted.
def chain_for(*a) :
    if a :
       for i in a :
          for j in i :
             yield j
    else :
       pass    

How can I emulate the same function in a class? Since the input to the function is an arbitrary number of lists, I am not sure if packing/unpacking can be used in classes, and if so I am not sure how to unpack in the 'init' method.

class chain_for :
   def __init__(self, ...) :
      ....
   def __iter__(self) :
      self
   def __next__(self) :
      .....

Thank you.


Solution

  • 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]