How to flatten nested list in python (5 ways)

featured Image

A list in python is one of the most flexible data types. It can have multiple dimensions i.e it can contain lists inside a list. It is known as the nested list.

When a list contains sublists in python, it is commonly known as a 2D list. And flattening a list of lists into a one-dimensional list is called flattening a list.

For example,[[1,2,3],[4,5,6]] is flatten into [1,2,3,4,5,6]

So let’s see how to merge nested lists into a single list in python.

Flatten a List in Python

There are a few different methods to flatten a nested list in python.

  1. Using for loop
  2. Using list comprehension
  3. Using reduce() function
  4. Using the itertools.chain() method
  5. Using numpy’s flat and concatenate function

Let’s see each method with examples.

Flatten a Nested List using for loop

We can flatten a nested list by using the nested for loop in python.

When a loop contains another loop inside we called it a nested for loop.

Since in a two-dimensional list, we have lists inside a list, so we have to loop through the first list and then loop through each item in the sub-list.

Example:

nested_list = [['a','b','c'],['d','e','f'],[7,8,9]]

flatten_list = []

for sub_list in nested_list:
    for item in sub_list:
        flatten_list.append(item)

print(flatten_list) 

Output:

['a', 'b', 'c', 'd', 'e', 'f', 7, 8, 9]

Here, we have the first loop through the sub list and then iterated through each item of the sub list and append it to the empty list i.e flatten_list.

Flatten List using List Comprehension

List comprehension is a shorthand syntax for creating a list based on existing lists in Python.

So, we can write the above for loop statement to merge and flatten the list using list comprehension.

nested_list = [['a','b','c'],['d','e','f'],[7,8,9]]

flatten_list = [item for sub_list in nested_list for item in sub_list]

print(flatten_list)

Output:

['a', 'b', 'c', 'd', 'e', 'f', 7, 8, 9]

Using reduce() method to Flatten List

We can use the reduce() function to merge the nested list in python. The reduce function is a part of the functools module.

The reduce() function does functional computation by taking in two arguments, a function and the list (sequence) as an argument.

Syntax:

reduce(function, iterable)

The function argument will be applied to all the elements of the iterable in a cumulative manner to output the result.

With the reduce function we can process the nested list without explicitly using the for loop statement.

from functools import reduce

nested_list = [['a','b','c'],['d','e','f'],[7,8,9]]

flatten_list = reduce(lambda a,b:a+b, nested_list)

print(flatten_list)

Output:

['a', 'b', 'c', 'd', 'e', 'f', 7, 8, 9]

Here, we have passed the lambda function as the first parameter and then the nested list.

The function will all the items in the list and print it out as an output.

Flatten List of lists using itertools module

To flatten a list of lists into a single list we can use the chain iterator of the itertools module.

The itertools module provides us with some utility functions that can be used to iterate over data structures that can be looped over using the for loop statement.

This module provides an iterator called chain(), which can help us to flatten a 2D list into a regular python list.

Example:

from itertools import chain

nested_list = [['a','b','c'],['d','e','f'],[7,8,9]]

flatten_list = list(chain(*nested_list))

print(flatten_list)

Output:

['a', 'b', 'c', 'd', 'e', 'f', 7, 8, 9]

Here, we pass on the nested list as a parameter to the chain() function.

The chain() function iterates through the first sublist, returns all the elements, and then moves to the second one, and so on until all the sublists are iterated through.

We then wrap the chain function with the list() to get the flat list of the elements.

Flatten List of Lists using numpy

Numpy is a library in python that provides different utility functions that can help us to flatten a nested list easily.

We can use the flat() and the concatenate() functions that can help to achieve our goal.

import numpy as np

nested_list = [['a','b','c'],['d','e','f'],[7,8,9]]

flatten_list = list(np.concatenate(nested_list).flat)

print(flatten_list)

Output:

['a', 'b', 'c', 'd', 'e', 'f', '7', '8', '9']

The output is a 1D flat array.

The concatenate() function concatenates a sequence of an array and the flat iterator is used to make a one-dimensional iterator over an array

Conclusion:

Here, we have learned four different ways to flatten a nested list in python. And also we used modules like itertools, functools, and numpy which helped to flatten the list of lists in python.


Other Articles You’ll Also Like:

Sort List or Dictionary by two keys in Python

Prepend List in Python (Append at the beginning)

Python – Check if list is empty or not

Remove Duplicates from List in Python

How to split a list into multiple list using python

Related Posts

merge json files in python

How to merge JSON files in python

JSON (JavaScript Object Notation) is a data format used for storing, transferring, and visualizing data. Its simple structure of key:value pairs and array data types makes JSON an easy and…

Read more
Install python pip in ubuntu

How to Install Pip(pip3) in Ubuntu Linux 22.04

Pip is a package manager for Python that allows you to install and manage additional Python packages that are not part of the Python standard library. Pip makes it easy…

Read more
featured Image

How to Write If-Else Statements in One Line in Python

If-else statements are a fundamental concept in Python and other programming languages. They allow you to execute different blocks of code based on whether a condition is true or false….

Read more

Leave a Reply

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