Convert List of Lists to Flat List in Python (One Liner)
Suppose you have a list of lists like [[12, 45, 67], [34, 56], [88, 90, 78], [111]]
. And you want to convert this to flat list like [12, 45, 67, 34, 56, 88, 90, 78, 111]
then you can use Python one liner as follow:
list_of_lists = [[12, 45, 67], [34, 56], [88, 90, 78], [111]]
flat_list = [element for sub_list in list_of_lists for element in sub_list]
print("Flat list: ", flat_list)
Output
Flat list: [12, 45, 67, 34, 56, 88, 90, 78, 111]
Above one liner code is equivalent to:
# one liner equivalent
flat_list = []
for sub_list in list_of_lists:
for element in sub_list:
flat_list.append(element)
Alternatively, you can use itertools
as follows:
import itertools
list_of_lists = [[12, 45, 67], [34, 56], [88, 90, 78], [111]]
flat_list = list(itertools.chain(*list_of_lists))
print("Flat list: ", flat_list)