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

Output: [1, 2, 3, 4, 5, 6]

Flatten List using Inbuilt reduce Function

Method 1:

Output: [14, 215, 383, 87, 298, 374, 2, 3, 4, 5, 6, 7]

Method 2:

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.

Output: [14, 215, 383, 87, 298, 374, 2, 3, 4, 5, 6, 7]

Flatten List Using List Compression

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.

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

Output: [14, 215, 383, 87, 298, 374, 2, 3, 4, 5, 6, 7]

The article was published on October 11, 2020 @ 1:42 PM

Leave a Comment