Search code examples
pythontuplesiterable-unpacking

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?


Solution

  • 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]