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.
Answers:
b = [i for sub in a for i in sub]
That will do the trick.
import itertools
b = [i for i in itertools.chain(*[(1,3),(5,4)])]
Just iterate over the list a and unpack the tuples:
l = []
for x,y in a:
l.append(x)
l.append(y)
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.
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
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.
b = [i for sub in a for i in sub]
That will do the trick.
import itertools
b = [i for i in itertools.chain(*[(1,3),(5,4)])]
Just iterate over the list a and unpack the tuples:
l = []
for x,y in a:
l.append(x)
l.append(y)
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.
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