0

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']
normanius
  • 8,629
  • 7
  • 53
  • 83
kushi s
  • 13
  • 2
  • `zip_iter = zip(repeat('a'),color)` you're using this in further tests so generator yields nothing in subsequent runs... – Jean-François Fabre Nov 22 '18 at 21:06
  • You must be using Python 3 as `zip` returns an iterable object. Once you've used it up, you can't use it again. – Peter Wood Nov 22 '18 at 21:28
  • Related: [Why can't I iterate twice over the same data?](https://stackoverflow.com/questions/25336726/why-cant-i-iterate-twice-over-the-same-data) – jpp Nov 22 '18 at 21:33

1 Answers1

1

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.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219