Create a flat list out of a list of lists in Python
Let’s take a list of lists.
Advertisements
list2d = [[1,2,3], [4,5,6], [7], [8,9]]
To merge this lists to a flat list you can use the following ways.
itertools.chain()
import itertools list2d = [[1,2,3], [4,5,6], [7], [8,9]] merged = list(itertools.chain(*list2d))
Advertisements
functools.reduce()
from functools import reduce list2d = [[1,2,3], [4,5,6], [7], [8,9]] reduce(lambda x, y: x+y, list2d) #[1, 2, 3, 4, 5, 6, 7, 8, 9]
list.extend()
list2d = [[1,2,3], [4,5,6], [7], [8,9]] out = [] for sublist in list2d: out.extend(sublist)