Search code examples
pythonpython-itertoolschain

Write a Python program to insert an element before each element of a list


In the below program what is the difference between the nested approach vs chain/chain.from_iterable as we get different outputs.

""" Write a Python program to insert an element before each element of a list. """ For instance:

from itertools import repeat, chain

def insertElementApproach2():
   color = ['Red', 'Green', 'Black']
   print("The pair element:")
   zip_iter = zip(repeat('a'),color)
   print((list(zip_iter)))

   print("The combined element using chain:")
   print(list(chain(zip_iter)))

   print("The combined element using chain.from_iterable:")
   print(list(chain(zip_iter)))

   print("Using the nested approach:")
   print(list(chain.from_iterable(zip(repeat('a'),color))))

   Output: 


The pair element:
   [('a', 'Red'), ('a', 'Green'), ('a', 'Black')]
   The combined element using chain:
   []
   The combined element using chain.from_iterable:
   []
   Using the nested approach:
   ['a', 'Red', 'a', 'Green', 'a', 'Black']

Solution

  • chain various approaches aren't the issue, your problem boils down to this:

    >>> a = zip([1],[2])
    >>> list(a)
    [(1, 2)]
    >>> list(a)
    []
    

    once you've iterated on your zip_iter variable, it yields nothing the second time, that's how zip works (range is able to be iterated more than once for instance, but that's because it takes integers as parameters, not iterables, that could be exhausted the second time it runs...)

    The last example works because you're re-creating a fresh zip object.