13

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 list of Tuples in Python

Community
  • 1
  • 1
David542
  • 104,438
  • 178
  • 489
  • 842
  • 2
    Flattening a list of tuples can be done in exactly the same ways to flattening a list of lists. See http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python, http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python, and many other answers. – Stuart Dec 13 '14 at 01:11
  • 3
    Does this answer your question? [How to make a flat list out of a list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) – Michael Hall Mar 24 '21 at 22:54

5 Answers5

19

You could use a list comprehension:

>>> 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 is also used a lot in cases like this:

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

That's not exactly a one-liner though.

  • I tried this with str values, and it appears to see the strings as collection of characters (which makes sense), any idea why? – dank8 Oct 30 '22 at 10:17
3
>>> INPUT = [(1,2),(1,),(1,2,3)]
>>> import itertools
>>> list(itertools.chain.from_iterable(INPUT))
[1, 2, 1, 1, 2, 3]
Tsingyi
  • 679
  • 6
  • 5
1

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.

Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
0
>>> INPUT = [(1,2),(1,),(1,2,3)]  
>>> import operator as op
>>> reduce(op.add, map(list, INPUT))
[1, 2, 1, 1, 2, 3]
Pavel Reznikov
  • 2,968
  • 1
  • 18
  • 17
  • This has quadratic behaviour (if you make the list ten times longer, it will be one hundred times slower) and so won't be a good idea for long lists. – DSM Dec 13 '14 at 01:13
  • I agree, it's much much better to use `itertools.chain.from_iterable` – Pavel Reznikov Dec 13 '14 at 01:22
0

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.

SmartElectron
  • 1,331
  • 1
  • 16
  • 17