3

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.

juniper-
  • 6,262
  • 10
  • 37
  • 65

2 Answers2

3

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]
Volatility
  • 31,232
  • 10
  • 80
  • 89
0

You can use reduce:

>>> import operator
>>> reduce(operator.add, [(3,4),(1,2)])
(3, 4, 1, 2)
Noel Evans
  • 8,113
  • 8
  • 48
  • 58
  • Why did this get downvoted? Just because it returns a tuple, rather than a list? – juniper- Mar 01 '13 at 10:34
  • @juniper It might have been because reduce was is deprecated in Python 3000. Guess it depends what version you're using. http://www.artima.com/weblogs/viewpost.jsp?thread=98196 – Noel Evans Mar 01 '13 at 10:39
  • @juniper I guess you know, but you can cast the output to a list with list(reduce(...)) – Noel Evans Mar 01 '13 at 10:41
  • The python 3000 thing is important, I suppose. Thanks! – juniper- Mar 01 '13 at 10:43
  • 1
    @juniper- maybe because `reduce(operator.add, ...` is really awful slow compared to `itertools.chain.from_iterable`. So some timing with larger inputs, and you'll notice a big difference. – sloth Mar 01 '13 at 10:44
  • Downvote is for useless and wrong answers, not for something that is corrrect, but not optimal. – Luka Rahne Mar 01 '13 at 10:48
  • @Dominic Kexel: Right you are. Nevertheless, it's still a valid answer. – juniper- Mar 01 '13 at 10:48
  • @juniper- Never said this answer is invalid, I just guessed that it was downvoted because of that. – sloth Mar 01 '13 at 10:49