Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

Convert Nested List To A Flat List In Python

2 min read

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 numpyli = [[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]


PYTHON

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read