in Python, How to join a list of tuples into one list?

Question:

Following on my previous question How to group list items into tuple?

If I have a list of tuples, for example

a = [(1,3),(5,4)]

How can I unpack the tuples and reformat it into one single list

b = [1,3,5,4]

I think this also has to do with the iter function, but I really don’t know how to do this. Please enlighten me.

Asked By: LWZ

||

Answers:

b = [i for sub in a for i in sub]

That will do the trick.

Answered By: Volatility
import itertools
b = [i for i in itertools.chain(*[(1,3),(5,4)])]
Answered By: danodonovan

Just iterate over the list a and unpack the tuples:

l = []
for x,y in a:
   l.append(x)
   l.append(y)
Answered By: Schuh
In [11]: list(itertools.chain(*a))
Out[11]: [1, 3, 5, 4]

If you just need to iterate over 1, 3, 5, 4, you can get rid of the list() call.

Answered By: NPE

Another way:

a = [(1,3),(5,4)]
b = []

for i in a:
    for j in i:
        b.append(j)

print b

This will only handle the tuples inside the list (a) tho. You need to add if-else statements if you want to parse in loose variables too, like;

a = [(1,3),(5,4), 23, [21, 22], {'somevalue'}]
b = []

for i in a:
    if type(i) == (tuple) or type(i) == (list) or type(i) == (set):
        for j in i:
            b.append(j)
    else:
        b.append(i)

print b
Answered By: user1467267
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.