Mastering List Flattening in Python: 3 Easy Methods

If you're looking to transform nested lists into a single, one-dimensional list efficiently, you've come to the right place.

This article will guide you through three simple techniques to flatten lists in Python.

1: Using List Comprehension

List comprehension offers a concise and Pythonic solution for flattening lists. Here's how you can do it:

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]

flat_list = [item for sublist in nested_list for item in sublist]

result:

[1, 2, 3, 4, 5, 6, 7, 8]

2: Using the itertools.chain Function

The itertools.chain function provides another elegant approach:.

It takes multiple iterables as arguments and returns a single iterable. In this case we pass a list of lists to get a single list which contains all nested items:

from itertools import chain

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]


flat_list = list(chain(*nested_list))

single dimension list from all nested lists:

[1, 2, 3, 4, 5, 6, 7, 8]

3: Flatten with numpy - for performance gain

For larger lists and better performance, NumPy offers efficient methods:

  • flat - equally sized lists
import numpy as np

nested_list = [[1, 2, 3], [4, 5, 6], [6, 7, 8]]

list(np.array(nested_list).flat)

single dimension list from all nested lists:

[1, 2, 3, 4, 5, 6, 6, 7, 8]
  • concatenate - different sublist lengths
import numpy as np

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]

list(np.concatenate(a))

single dimension list from all nested lists:

[1, 2, 3, 4, 5, 6, 7, 8]

To read more on performance related to flattening list of lists check: Flatten list of lists - benchmark in Python

Bonus: Flatten MultiIndex in Pandas

To flatten Pandas MultiIndex we can use the following code:

df.columns = df.columns.to_flat_index()

More ways and example to flatten columns in Pandas: Flatten column MultiIndex with method

Summary

Whether it's list comprehension, itertools, or NumPy, each method offers its advantages. Mastering list flattening techniques is invaluable, particularly when dealing with diverse datasets or nested structures.

With these three methods at your disposal, you're well-equipped to handle list flattening in Python efficiently.

Now, you have three easy ways to flatten lists in Python.

Resources