Quickly learn how to flatten nested lists in Python. If you need a short and easy way to flatten a list of lists into a single, one-dimensional list then read till the end.
Operation of conversion of nested lists of lists to a single one is often referred to as "flattening" and can be accomplished using various methods. In this article, we'll explore a few simple techniques to make a flat list out of a list of lists.
1: Using List Comprehension
List comprehension offers a Pythonic and concise way to:
- iterate through each sublist and item within the sublists
- creating a flat list
Below you can find how to flatten the list using list comprehension:
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 is 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
Finally if you need to get faster solution for bigger lists we can use two methods from numpy:
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
Choose the method that suits your coding style and specific requirements. Flattening lists is a useful skill, especially when working with diverse datasets or nested structures. Mastering these techniques will enhance your proficiency in Python programming.
Now you have 3 easy ways to flatten lists in Python.