Coding Ref

Flatten a list in Python

Flatten a list in Python

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.

main.py
# 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:

main.py
# 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.

main.py
def flatten_list(original_list):
  return [item for sublist in original_list for item in sublist]

An alternative is to use itertools.chain().

main.py
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))

Conclusion

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].

You'll also like

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