In this tutorial, we will go through several methods to convert a Nested list to flat list using Python
.
Lists are probably the most used data type in Python. Lists being mutable offer a lot of flexibility to perform a number of operations on the items of the list.
A list contains items separated by commas and enclosed within square brackets [ ]. Lists in Python
can also have items of different data types
together in a single list. A nested list is nothing but a list containing several lists for example [1,2,[3],[4,[5,6]]
Often we need to convert these nested lists to flat list
to perform regular list operations on the data. Fortunately, in Python, there are many ways to achieve this.
Convert Nested List To Flat List In Python
1 2 3 4 5 6 7 |
def flatten(li): return sum(([x] if not isinstance(x, list) else flatten(x) for x in li), []) print(flatten([1, 2, [3], [4, [5, 6]]])) |
Output: [1, 2, 3, 4, 5, 6]
Flatten List using Inbuilt reduce Function
Method 1:
1 2 3 4 5 6 7 8 |
import functools import operator li = [[14], [215, 383, 87], [298], [374], [2, 3, 4, 5, 6, 7]] flat_list = functools.reduce(operator.concat, li) print(flat_list) |
Output: [14, 215, 383, 87, 298, 374, 2, 3, 4, 5, 6, 7]
Method 2:
1 2 3 4 5 6 7 |
from functools import reduce li = [[14], [215, 383, 87], [298], [374], [2, 3, 4, 5, 6, 7]] flat_list = reduce(lambda x, y: x+y, li) print(flat_list) |
Output: [14, 215, 383, 87, 298, 374, 2, 3, 4, 5, 6, 7]
Method 3:
This is one of the most efficient ways to flatten a large list.
1 2 3 4 5 6 7 |
from itertools import chain li = [[14], [215, 383, 87], [298], [374], [2, 3, 4, 5, 6, 7]] flat_list = list(chain.from_iterable(li)) print(flat_list) |
Output: [14, 215, 383, 87, 298, 374, 2, 3, 4, 5, 6, 7]
Flatten List Using List Compression
1 2 3 4 5 |
li = [[14], [215, 383, 87], [298], [374], [2, 3, 4, 5, 6, 7]] flat_list = [item for sublist in li for item in sublist] print(flat_list) |
Output: [14, 215, 383, 87, 298, 374, 2, 3, 4, 5, 6, 7]
Flatten List Using NumPy
Note that, NumPy doesn’t come bundled with Python Installation you have to install it which can be done simply using Pip Installer.
1 2 3 |
pip install numpy |
Once the installation is done you can run the code below,
1 2 3 4 5 6 7 |
import numpy li = [[14], [215, 383, 87], [298], [374], [2, 3, 4, 5, 6, 7]] flat_list = list(numpy.concatenate(li).flat) print(flat_list) |
Output: [14, 215, 383, 87, 298, 374, 2, 3, 4, 5, 6, 7]
Leave a Comment