How to Make a Flat List Out of a List of Lists in Python?

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]

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?