To flatten a list of lists in Python, you can use list comprehension or the itertools.chain
function. Here’s how you can do it using list comprehension:
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)
Output:
[
]
Alternatively, you can use itertools.chain
:
from itertools import chain
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat_list = list(chain.from_iterable(nested_list))
print(flat_list)
Output:
[
]Both approaches will give you a flat list containing all the elements from the nested lists.