How can I transform, with list comprehension, a list of tuple list to tuple list?
Example:
convert [[(1, 2, 3), (4, 5, 6)], [(7, 8, 9), (10, 11, 12)]]
to [(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)]
How can I transform, with list comprehension, a list of tuple list to tuple list?
Example:
convert [[(1, 2, 3), (4, 5, 6)], [(7, 8, 9), (10, 11, 12)]]
to [(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)]
You can do it like this, using list comprehension:
list_ = [[(1, 2, 3), (4, 5, 6)], [(7, 8, 9), (10, 11, 12)]]
flat_list = [item for sublist in list_ for item in sublist]
print(flat_list)
Or as a function:
def flat_list(list_):
return [item for sublist in list_ for item in sublist]
if __name__ == '__main__':
print(flat_list([[(1, 2, 3), (4, 5, 6)], [(7, 8, 9), (10, 11, 12)]]))
Another common way of doing this would be to use the the itertools
module:
def flat_list(list_):
return list(itertools.chain.from_iterable(list_))
From the linked SO question, you can also see some timings.