Opposite of zip(*[iter(s)]*n)

Question:

Dividing a list into equal chunks is neatly done using the zip(*[iter(s)]*n) idiom. Is there a nice way of undoing it?

For example, if I have the following code:

>>> s = [3,4,1,2]
>>> zip(*[iter(s)]*2)
[(3, 4), (1, 2)]

Is there some function func([(3,4),(1,2)] that will yield [3,4,1,2] as the output?

Edit:

Timing and more solutions can be found in the question linked to by Dominic Kexel below.

Asked By: juniper-

||

Answers:

There is itertools.chain.from_iterable

>>> import itertools
>>> s = [(3, 4), (1, 2)]
>>> list(itertools.chain.from_iterable(s))
[3, 4, 1, 2]

However you could also use a nested list comprehension.

>>> s = [(3, 4), (1, 2)]
>>> [i for sub in s for i in sub]
[3, 4, 1, 2]
Answered By: Volatility

You can use reduce:

>>> import operator
>>> reduce(operator.add, [(3,4),(1,2)])
(3, 4, 1, 2)
Answered By: Noel Evans
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.