How to Make a Flat List Out of a List of Lists in Python?
To make a flat list out of a list of lists in Python, you can use the built-in function itertools.chain
and the *
operator to unpack the nested lists.
For example, consider the following list of lists:
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
You can convert this into a flat list as follows:
import itertools
flat_list = list(itertools.chain(*nested_list))
print(flat_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Alternatively, you can also use a list comprehension to achieve the same result:
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]