To flatten a list of lists or a nested list in Python, use the code, flat_list = [item for sublist in original_list for item in sublist]
.
To flatten a list that looks like the following.
# We want to make this list
original_list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
# 👇 Look like this list
flat_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Use the following code:
# Given a list of lists `original_list`
flat_list = [item for sublist in original_list for item in sublist]
# 👇 This code translates into:
flat_list = []
for sublist in original_list:
for item in sublist:
flat_list.append(item)
You can create a reuseable function.
def flatten_list(original_list):
return [item for sublist in original_list for item in sublist]
An alternative is to use itertools.chain()
.
import itertools
original_list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
# Method 1 requires the use of the `*` operator
flat_list = list(itertools.chain(*original_list))
# Method 2 does not require the use of the `*` operator
flat_list = list(itertools.chain.from_iterable(original_list))
To flatten a list of lists or a nested list in Python, use the code, flat_list = [item for sublist in original_list for item in sublist]
.
Related tutorials curated for you
Convert JSON to CSV in Python
TypeError: string indices must be integers
ModuleNotFoundError: No module named 'pip' in Python
Delete Conda environment
How to fix: Unindent does not match any outer indentation level in Python
SyntaxError: unexpected EOF while parsing
ModuleNotFoundError: No module named 'matplotlib' in Python
How to fix: Can only use .str accessor with string values, which use np.object_ dtype in pandas
TypeError: only integer scalar arrays can be converted to a scalar index
TypeError: a bytes-like object is required, not 'str'
IndexError: list index out of range
ModuleNotFoundError: No module named 'cv2' in Python