How to flatten a list of tuples into a pythonic list

Given the following list of tuples:

INPUT = [(1,2),(1,),(1,2,3)]

      

How would I flatten it into a list?

OUTPUT ==> [1,2,1,1,2,3]

      

Is there a one-liner to do the above?

Similar: Flatten a list of tuples in Python

+5


source to share


5 answers


You can use understanding:

>>> INPUT = [(1,2),(1,),(1,2,3)]
>>> [y for x in INPUT for y in x]
[1, 2, 1, 1, 2, 3]
>>>

      

itertools.chain.from_iterable

also used a lot in such cases:



>>> from itertools import chain
>>> INPUT = [(1,2),(1,),(1,2,3)]
>>> list(chain.from_iterable(INPUT))
[1, 2, 1, 1, 2, 3]
>>>

      

It's not quite a one-liner.

+9


source


>>> INPUT = [(1,2),(1,),(1,2,3)]
>>> import itertools
>>> list(itertools.chain.from_iterable(INPUT))
[1, 2, 1, 1, 2, 3]

      



+2


source


You can use sum

which adds all the elements if it is a list from a list (nested singly).

sum([(1,2),(1,),(1,2,3)], ())

      

or convert to list:

list(sum([(1,2),(1,),(1,2,3)], ()))

      

Adding lists works in Python.

Note : this is very inefficient and some say it is unreadable.

+1


source


>>> INPUT = [(1,2),(1,),(1,2,3)]  
>>> import operator as op
>>> reduce(op.add, map(list, INPUT))
[1, 2, 1, 1, 2, 3]

      

0


source


Not in one line, but in two:

>>> out = []
>>> map(out.extend, INPUT)
... [None, None, None]
>>> print out
... [1, 2, 1, 1, 2, 3]

      

Declare a list object and use the extension.

0


source







All Articles