Convert Nested List To A Flat List In 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 list into a flat list to perform regular list operations on the data. Fortunately, in Python, there are many ways to achieve this.

In this tutorial, we will go through several methods to convert a Nested list into a flat regular list.

Convert Nested List To A Flat List In Python

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:

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:

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.

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

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.

pip install numpy

Once the installation is done you can run the code below,

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]

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Close