Convert list of tuples to list?

>>> a = [(1,), (2,), (3,)]
>>> zip(*a)[0]
(1, 2, 3)

For a list:

>>> list(zip(*a)[0])
[1, 2, 3]

Using simple list comprehension:

e = [(1,), (2,), (3,)]
[i[0] for i in e]

will give you:

[1, 2, 3]

@Levon's solution works perfectly for your case.

As a side note, if you have variable number of elements in the tuples, you can also use chain from itertools.

>>> a = [(1, ), (2, 3), (4, 5, 6)]
>>> from itertools import chain
>>> list(chain(a))
[(1,), (2, 3), (4, 5, 6)]
>>> list(chain(*a))
[1, 2, 3, 4, 5, 6]
>>> list(chain.from_iterable(a)) # More efficient version than unpacking
[1, 2, 3, 4, 5, 6]

Here is another alternative if you can have a variable number of elements in the tuples:

>>> a = [(1,), (2, 3), (4, 5, 6)]
>>> [x for t in a for x in t]
[1, 2, 3, 4, 5, 6]

This is basically just a shortened form of the following loops:

result = []
for t in a:
    for x in t:
        result.append(x)

Tags:

Python