Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Merge an Arbitrary Number of Tuples in Python?

I have a list of tuples:

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

The list can be of arbitrary length, as can the tuples. I'd like to convert this into a list or tuple of the elements, in the order they appear:

f=[1,2,3,4,5,6] # or (1,2,3,4,5,6)

If I know the at development time how many tuples I'll get back, I could just add them:

m = l[0] + l[1]  # (1,2,3,4,5,6)

But since I don't know until runtime how many tuples I'll have, I can't do that. I feel like there's a way to use map to do this, but I can't figure it out. I can iterate over the tuples and add them to an accumulator, but that would create lots of intermediate tuples that would never be used. I could also iterate over the tuples, then the elements of the tuples, and append them to a list. This seems very inefficient. Maybe there's an even easier way that I'm totally glossing over. Any thoughts?

like image 915
technomalogical Avatar asked Feb 22 '12 18:02

technomalogical


3 Answers

Chain them (only creates a generator instead of reserving extra memory):

>>> from itertools import chain
>>> l = [(1,2,3),(4,5,6)]
>>> list(chain.from_iterable(l))
[1, 2, 3, 4, 5, 6]
like image 87
AndiDog Avatar answered Oct 26 '22 02:10

AndiDog


l = [(1, 2), (3, 4), (5, 6)]
print sum(l, ()) # (1, 2, 3, 4, 5, 6)
like image 20
Cat Plus Plus Avatar answered Oct 26 '22 03:10

Cat Plus Plus


reduce(tuple.__add__, [(1,2,3),(4,5,6)])
like image 21
bluepnume Avatar answered Oct 26 '22 04:10

bluepnume