How to make two lists out of two-elements tuples that are stored in a list of lists of tuples

Your approach is quite close, but you need to flatten first:

from itertools import chain

my_list = [[(12, 1), (10, 3), (4, 0), (2, 0)], [(110, 1), (34, 2), (12, 1), (55, 3)]]

my_list2 , my_list3 = map(list,zip(*chain.from_iterable(my_list)))

my_list2
# [12, 10, 4, 2, 110, 34, 12, 55]

my_list3
# [1, 3, 0, 0, 1, 2, 1, 3]

A different, plain approach:

my_list = [[(12, 1), (10, 3), (4, 0), (2, 0)], [(110, 1), (34, 2), (12, 1), (55, 3)]]

first = []
second = []

for inner in my_list:
    for each in inner:
        first.append(each[0])
        second.append(each[1])

print(first)  # [12, 10, 4, 2, 110, 34, 12, 55]
print(second)  # [1, 3, 0, 0, 1, 2, 1, 3]

You can use list comprehension (5.1.3).

First number of tuple:

my_list2 = [tuple[0] for inner in my_list for tuple in inner]

Second number of tuple:

my_list3 = [tuple[1] for inner in my_list for tuple in inner]

Tags:

Python

List