Skip to content Skip to sidebar Skip to footer

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: Fl

Solution 1:

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

Solution 2:

you can use sum which adds up all of the elements if it's a list of list (singly-nested).

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

or convert to list:

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

Adding up lists works in python.

Note: This is very inefficient and some say unreadable.

Solution 3:

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

Solution 4:

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 extend.

Post a Comment for "How To Flatten A List Of Tuples Into A Pythonic List"