Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack list of lists into list [duplicate]

I have list of lists of tuples:

a = [[(1, 2), (3, 4), (5, 6)], [(7, 8), (9, 10)]]

How can I make one list of tuples:

b = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]

Naive way is:

b = []
for c in a:
    for t in c:
        b.append(t)

List comprehension or any other ideas are welcome.

like image 566
torayeff Avatar asked May 05 '18 18:05

torayeff


1 Answers

Using itertools

demo:

import itertools
a = [[(1, 2), (3, 4), (5, 6)], [(7, 8), (9, 10)]]
print(list(itertools.chain(*a)))

Output:

[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
like image 101
Rakesh Avatar answered Sep 20 '22 03:09

Rakesh