tags:

views:

207

answers:

3

I need to do the opposite of this

http://stackoverflow.com/questions/756550/multiple-tuple-to-two-pair-tuple-in-python

Namely, I have a list of tuples

[(1,2), (3,4), (5,6)]

and need to produce this

[1,2,3,4,5,6]

I would personally do this

>>> tot = []
>>> for i in [(1,2), (3,4), (5,6)]:
...     tot.extend(list(i))

but I'd like to see something fancier.

+14  A: 

The most efficient way to do it is this:

tuples = [(1,2), (3,4), (5,6)]
[item for t in tuples for item in t]

output

[1, 2, 3, 4, 5, 6]

Here is the comparison I did for various way to do it in a duplicate question.

I know someone is going to suggest this solution

sum(tuples, ())

But don't use it, it will create a new intermediate result list for each step! unless you don't care about performance and just want a compact solution. For more details check Alex's answer

In summary: sum is faster for small lists, but the performance degrades significantly with larger lists.

Nadia Alramli
definitely very elegant.
Stefano Borini
+2  A: 
l = [(1,2), (3,4), (5,6)]
reduce (lambda x,y: x+list(y), l, [])
eduffy
If you go that way, `sum()` is simpler (but this approach creates a lot of intermediary lists).
tonfa
+6  A: 
>>> import itertools
>>> tp = [(1,2),(3,4),(5,6)]
>>> lst = list(itertools.chain(*tp))
>>> lst
[1, 2, 3, 4, 5, 6]

Of course, if you don't need a list but an iterator, you can drop the list() conversion call.

Tim Pietzcker
you're showing how to chain three tuples, not a single list containing three tuples
SilentGhost
Or: lst = list(chain.from_iterable(tp))
dangph
I already edited it, but it wasn't just three tuples but a "tuple of three tuples" - now changed to a list of tuples...
Tim Pietzcker
tuples of three tuples needs to have additional brackets when passed to function
SilentGhost