Flattening Nested Lists in Python

Flattening Nested Lists In Python

Python lists can be nested in the form of 2d structures as a replacement for arrays in other languages. Since python doesn’t have an array data type, it uses lists to create these 2d, 3d or sometimes N-dimensional arrays.

Flattening refers to the process of reducing 2d arrays into 1 dimensional list. It collects all the elements from the nested lists and combine them into one list.

There are many ways in which we can convert a list of lists into just one list in python. Let’s look at some of the methods.

If you want to know more about the different data types that are available in python, we have an awesome course for you!

Method 1: Using the reduce() function

A built-in function called reduce() can be used to reduce 2d lists into one big list. We have to import the library functools in our program in order to use the reduce() function.

If you don’t have the library installed/updated, run pip install functools in your command prompt. It is a library that contains fast tools for high function programming.

Also , the function concat() from the operator module has to be used in addition to the reduce() function in order to concatenate the sub-lists into one giant list. The concat() function has to be passed as an argument for the reduce() function.

The reduce() function takes in two parameters: The first one which defines the concatenation of the inner lists, and the second argument is the required list that needs to be reduced.

Let’s look at how the function can be used to break down lists of list into one giant list.

#import required modules
from functools import reduce
from operator import concat
#declaring our list
lst=[[1,2],[3,4],[5,6,7],['bye','hi']]
print("The original list is=",lst)
#reducing the list
flat=reduce(concat,lst)
#displaying the flattening of the list
print("the reduced list is=",flat)

The output is:

The original list is= [[1, 2], [3, 4], [5, 6, 7], ['bye', 'hi']]
the reduced list is= [1, 2, 3, 4, 5, 6, 7, 'bye', 'hi']
Using The Reduce() Function
Using The Reduce() Function

Also read: Python Built-in Functions: Brief Overview.

Method 2: Using nested loops

This method is more mechanical than the previous one. It uses nested for loops to traverse through the individual lists one by one and concatenate each of them into one huge list. Let’s look at how this can be done.

lst=[["Happy","surfing","on"],["ask"],["python"]] #the original 2d list
#displaying original list
print("The original list is =",lst)
#creating the flattening list
flat=[]
#nested loop crreation
for i in lst:
    for j in i:
        flat.append(j)
#displaying our results
print("The flattened list is=",flat)

The output of our above code will be:

The original list is = [['Happy', 'surfing', 'on'], ['ask'], ['python']]
The flattened list is= ['Happy', 'surfing', 'on', 'ask', 'python']
Using Nested For Loops
Using Nested For Loops

Method 3: Using list comprehension methods

In this method we will use the list comprehension methods take make flattening lists easier. It can be done in just one line so let’s take user input for this example.

lst=[] #the original list and the sublists
#determining size of list from user input
N=int(input("Enter the size of the bigger list="))
#taking input
for i in range(N):
  size=int(input("Enter the size of "+ str(i+1)+" nested list= "))
  sublst=[]
  for j in range(size):
    inp=input("enter the "+str(j+1)+" element of the "+ str(i+1)+" nested list= ")
    sublst.append(inp)
  lst.append(sublst)
#displaying original list
print("The original list is =",lst)
#using list comprehension
flat=[element for sublst in lst for element in sublst]
#displaying our results
print("The flattened list is=",flat)

The output of the above code would be:

Enter the size of the bigger list=2
Enter the size of 1 nested list= 2
enter the 1 element of the 1 nested list= one
enter the 2 element of the 1 nested list= two
Enter the size of 2 nested list= 2
enter the 1 element of the 2 nested list= three
enter the 2 element of the 2 nested list= four
The original list is = [['one', 'two'], ['three', 'four']]
The flattened list is= ['one', 'two', 'three', 'four']
Using List Comprehension On User Defined Lists
Using List Comprehension On User Defined Lists

Summary

This tutorial covers three ways in which we flatten a list of lists into one big list. Flattening a list in python is very easy due to a huge availability of resources and in-built functions. Reducing the dimensions of a list can help improve performance and, in some cases, can also simplify calculations. List comprehension is a huge part of python programming. To know more about python lists, visit the official site.