Search code examples
pythontupleslist-comprehensioniterable-unpacking

How do I convert a tuple of tuples to a one-dimensional list using list comprehension?


I have a tuple of tuples - for example:

tupleOfTuples = ((1, 2), (3, 4), (5,))

I want to convert this into a flat, one-dimensional list of all the elements in order:

[1, 2, 3, 4, 5]

I've been trying to accomplish this with list comprehension. But I can't seem to figure it out. I was able to accomplish it with a for-each loop:

myList = []
for tuple in tupleOfTuples:
   myList = myList + list(tuple)

But I feel like there must be a way to do this with a list comprehension.

A simple [list(tuple) for tuple in tupleOfTuples] just gives you a list of lists, instead of individual elements. I thought I could perhaps build on this by using the unpacking operator to then unpack the list, like so:

[*list(tuple) for tuple in tupleOfTuples]

or

[*(list(tuple)) for tuple in tupleOfTuples]

... but that didn't work. Any ideas? Or should I just stick to the loop?


Solution

  • it's typically referred to as flattening a nested structure.

    >>> tupleOfTuples = ((1, 2), (3, 4), (5,))
    >>> [element for tupl in tupleOfTuples for element in tupl]
    [1, 2, 3, 4, 5]
    

    Just to demonstrate efficiency:

    >>> import timeit
    >>> it = lambda: list(chain(*tupleOfTuples))
    >>> timeit.timeit(it)
    2.1475738355700913
    >>> lc = lambda: [element for tupl in tupleOfTuples for element in tupl]
    >>> timeit.timeit(lc)
    1.5745135182887857
    

    ETA: Please don't use tuple as a variable name, it shadows built-in.