Open In App

Python | Ways to flatten a 2D list

Last Updated : 18 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a 2D list, Write a Python program to convert the given list into a flattened list. 

Method #1: Using chain.iterable() 

Python3




# Python code to demonstrate
# converting 2d list into 1d list
# using chain.from_iterables
 
# import chain
from itertools import chain
 
ini_list = [[1, 2, 3],
            [3, 6, 7],
            [7, 5, 4]]
             
# printing initial list
print ("initial list ", str(ini_list))
 
# converting 2d list into 1d
# using chain.from_iterables
flatten_list = list(chain.from_iterable(ini_list))
 
# printing flatten_list
print ("final_result", str(flatten_list))


Output: 

initial list  [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
final_result [1, 2, 3, 3, 6, 7, 7, 5, 4]

 

The time complexity of the code is O(m*n) where m is the number of lists and n is the maximum length of the lists. 

The auxiliary space complexity of the code is O(mn) because a new list of size mn is created to store the flattened list. 

Python3




# Python code to demonstrate
# converting 2d list into 1d list
# using list comprehension
 
# import chain
from itertools import chain
 
ini_list = [[1, 2, 3],
            [3, 6, 7],
            [7, 5, 4]]
             
# printing initial list
print ("initial list ", str(ini_list))
 
# converting 2d list into 1d
# using list comprehension
flatten_list = [j for sub in ini_list for j in sub]
 
# printing flatten_list
print ("final_result", str(flatten_list))


Output: 

initial list  [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
final_result [1, 2, 3, 3, 6, 7, 7, 5, 4]

 

The time complexity of this program is O(mn), where m is the number of rows and n is the number of columns in the input 2D list. 

The space complexity of this program is O(mn), as the size of the output list is proportional to the size of the input list. 

Method #3: Using functools.reduce  

Python3




# Python code to demonstrate
# converting 2d list into 1d list
# using functools.reduce
 
# import functools
from functools import reduce
 
ini_list = [[1, 2, 3],
            [3, 6, 7],
            [7, 5, 4]]
             
# printing initial list
print ("initial list ", str(ini_list))
 
# converting 2d list into 1d
# using functools.reduce
flatten_list = reduce(lambda z, y :z + y, ini_list)
 
# printing flatten_list
print ("final_result", str(flatten_list))


Output: 

initial list  [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
final_result [1, 2, 3, 3, 6, 7, 7, 5, 4]

 

The time complexity of the above code is O(N^2) as it has to traverse all the elements in a 2D list once.
The space complexity is also O(N^2), as the entire input list needs to be stored in memory and a new list is created to store the flattened version of the list. 

Method #4: Using sum
sum has an optional argument: sum(iterable [, start])

Python3




# Python code to demonstrate
# converting 2d list into 1d list
# using sum
 
ini_list = [[1, 2, 3],
            [3, 6, 7],
            [7, 5, 4]]
 
# printing initial list
print ("initial list ", str(ini_list))
 
# converting 2d list into 1d
flatten_list = sum(ini_list, [])
 
# printing flatten_list
print ("final_result", str(flatten_list))
 
# This code is contributed by
# Mayank Chaudhary - chaudhary_19


Output: 

initial list  [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
final_result [1, 2, 3, 3, 6, 7, 7, 5, 4]

Time Complexity: The time complexity of this program is O(mn), where m is the number of rows and n is the number of columns in the input 2D list.
Auxiliary Space: The auxiliary space of this program is O(mn), as the size of the output list is proportional to the size of the input list. 
Method #5: Using lambda  

Python3




#Python 3 code to flatten nested list
#contributed by S Lakshman Rao - kaapalx
ini_list=[[1, 2, 3],
          [3, 6, 7],
          [7, 5, 4]]
 
#Using lambda
 
flatten_list = lambda y:[x for a in y for x in flatten_list(a)] if type(y) is list else [y]
 
print("Initial list ",ini_list) #printing initial list
 
print("Flattened List ",flatten_list(ini_list)) # printing flattened list


Output: 

Initial list  [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
Flattened List  [1, 2, 3, 3, 6, 7, 7, 5, 4]

Method #6: Using numpy  

Python3




#Python 3 code to flatten nested list
#Contributed by S Lakshman Rao - kaapalx
import numpy
 
ini_list=[[1, 2, 3],
          [3, 6, 7],
          [7 ,5, 4]]
 
print("Initial list ",ini_list) #Printing Initial list
 
print("Flattened List ",list(numpy.concatenate(ini_list).flat))
#Using numpy to flatten list and printing the result


Output: 

Initial list  [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
Flattened List  [1, 2, 3, 3, 6, 7, 7, 5, 4]

The time complexity of this program is O(N^2) where N is the number of elements in the nested list.

The auxiliary space complexity is O(N), as the flattened list is stored in memory as a new list.

 Method #7: Using extend() method

Python3




#Python 3 code to flatten nested list
 
ini_list=[[1, 2, 3],[3, 6, 7],[7 ,5, 4]]
print("Initial list ",ini_list) #Printing Initial list
res=[]
for i in ini_list:
    res.extend(i)
print("Flattened List ",res)


Output

Initial list  [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
Flattened List  [1, 2, 3, 3, 6, 7, 7, 5, 4]


Previous Article
Next Article

Similar Reads

Python | Sort Flatten list of list
The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let's discuss certain ways in which this can be done. Method #1 : Using sorted() + list comprehension This idea is similar to flattening a list of list but in addition to it, we add a sorted
7 min read
Python program to Flatten Nested List to Tuple List
Given a list of tuples with each tuple wrapped around multiple lists, our task is to write a Python program to flatten the container to a list of tuples. Input : test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]Output : [(4, 6), (7, 4), (10, 3)]Explanation : The surrounded lists are omitted around each tuple. Input : test_list = [[[(4, 6)]],
7 min read
Python | Flatten given list of dictionaries
Given a list of the dictionaries, the task is to convert it into single dictionary i.e flattening a list of dictionaries. Given below are a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # to flatten list of dictionaries # Initialising dictionary ini_dict = [{'a':1}, {'b':2}, {'c':3}] # pr
4 min read
Python | Flatten Tuples List to String
Sometimes, while working with data, we can have a problem in which we need to perform interconversion of data. In this, we can have a problem of converting tuples list to a single String. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + join() The combination of above functionalities can be used
7 min read
Python | Split flatten String List
Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split() + extend() The combination of a
7 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python - Flatten Dictionary with List
Given a list and dictionary, flatten dictionary with keys and values at position of available element of key in list. Input : test_list = ["Gfg", "is", "Best", "For", "Geeks"], subs_dict = {"Gfg" : 7} Output : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks'] Explanation : "Gfg" is replaced, followed by its value in dictionary. Input : test_list = ["Gfg", "
4 min read
Python Program to Flatten a Nested List using Recursion
Given a nested list, the task is to write a python program to flatten a nested list using recursion. Examples: Input: [[8, 9], [10, 11, 'geeks'], [13]] Output: [8, 9, 10, 11, 'geeks', 13] Input: [['A', 'B', 'C'], ['D', 'E', 'F']] Output: ['A', 'B', 'C', 'D', 'E', 'F'] Step-by-step Approach: Firstly, we try to initialize a variable into the linked l
3 min read
Python Program to Flatten a List without using Recursion
The task is to convert a nested list into a single list in Python i.e no matter how many levels of nesting are there in the Python list, all the nested have to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside. In other words, an element in a list c
7 min read
Python Program To Flatten A Multi-Level Linked List Depth Wise- Set 2
We have discussed flattening of a multi-level linked list where nodes have two pointers down and next. In the previous post, we flattened the linked list level-wise. How to flatten a linked list when we always need to process the down pointer before next at every node. Input: 1 - 2 - 3 - 4 | 7 - 8 - 10 - 12 | | | 9 16 11 | | 14 17 - 18 - 19 - 20 |
4 min read
Practice Tags :
three90RightbarBannerImg