Sometimes, while working with a Python list, we can have a problem in which we need to perform flattening,i.e., of the list, i.e. convert a mixed list to a flattened one. This can have applications in domains that use 1D lists as input. Let’s discuss certain ways in which this task can be performed.
Input: [[1,3, "Lazyroar"], [4,5], [6, "best"]]
Output: [1, 3, 'Lazyroar', 4, 5, 6, 'best']
Explaination: flattening Convert a mixed list to a flattened one.
Flatten the List to Individual Element
Below are the methods that we will cover in this article:
- Flatten List using list comprehension
- Flatten List using sum()
- Flatten List using loop
- Flatten List using flatten() method
- Flatten List using chain() with isinstance()
- Flatten List using reduce() function
Flatten List using list comprehension
Here, we are using list comprehension to flatten the list from 2D to 1D.
Python3
res = [i for row in [[ 1 , 3 , "Lazyroar" ], [ 4 , 5 ], [ 6 , "best" ]] for i in row] print (res) |
Output:
[1, 3, 'Lazyroar', 4, 5, 6, 'best']
Time Complexity: O(n) where n is the number of elements in the list
Auxiliary Space: O(n) where n is the number of elements in the list
Flatten List using sum()
Here, we are using the sum() function in which we passed test_list as an iterable object as the first parameter and the second parameter as an empty list in which it stores the element.
Python3
test_list = [[ 1 , 3 , "gfg" ], [ 4 , 5 ], [ 6 , "best" ]] test_list = sum (test_list, []) print (test_list) |
Output:
[1, 3, 'gfg', 4, 5, 6, 'best']
Time Complexity: O(n), where n is the length of the list test_list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list
Flatten List using loop
The combination of the above functionalities can be used to perform this task. In this, we check for an instance of the list and flatten it, and the rest of the elements we add to the list brutely.
Python3
def flatten(test_list): if isinstance (test_list, list ): temp = [] for ele in test_list: temp.extend(flatten(ele)) return temp else : return [test_list] # Initializing list test_list = [ 'gfg' , 1 , [ 5 , 6 , 'Lazyroar' ], 67.4 , [ 5 ], 'best' ] # Flatten List to individual elements # using loop + isinstance() res = flatten(test_list) # printing result print ( "The List after flattening : " + str (res)) |
Output:
The List after flattening : [‘gfg’, 1, 5, 6, ‘Lazyroar’, 67.4, 5, ‘best’]
Time complexity: of this function is O(n), where n is the total number of elements in the nested list.
Space complexity: of this function is also O(n), as a new list temp is created for each recursive call to store the flattened sublist, and the final flattened list is stored in the res variable.
Flatten List using flatten() method
Pandas flatten return a copy of the array collapsed into one dimension.
Python3
from pandas.core.common import flatten l = [[ 1 , 3 , "gfg" ], [ 4 , 5 ], [ 6 , "best" ]] print ( list (flatten(l))) |
Output:
[1, 3, 'gfg', 4, 5, 6, 'best']
Flatten List using chain() with isinstance()
This is yet another way in which this task can be performed. In this, which we perform the task of iteration using chain() and checking for list instances, which is done using isinstance().
Python3
from itertools import chain # Initializing list test_list = [ 'gfg' , 1 , [ 5 , 6 , 'Lazyroar' ], 67.4 , [ 5 ], 'best' ] # Flatten List to individual elements # using chain() + isinstance() res = list (chain( * [ele if isinstance (ele, list ) else [ele] for ele in test_list])) # printing result print ( "The List after flattening : " + str (res)) |
Output :
The List after flattening : [‘gfg’, 1, 5, 6, ‘Lazyroar’, 67.4, 5, ‘best’]
Time complexity: O(n)
Auxiliary Space: O(n)
Flatten List using reduce() function
The reduce() function is defined in the “functools” module. It applies a function of two arguments continuously on the given sequence and returns a single value.
Python3
from functools import reduce # Initializing list test_list = [[ 1 , 3 , "gfg" ], [ 4 , 5 ], [ 6 , "best" ]] # Flatten List to individual elements # using reduce() res = reduce ( lambda x,y: x + y, test_list) # printing result print ( "The List after flattening : " + str (res)) #This code is contributed by Edula Vinay Kumar Reddy |
The List after flattening : [1, 3, 'gfg', 4, 5, 6, 'best']
Time complexity: O(n)
Auxiliary Space: O(n)
Flatten List to individual elements using groupby:
Import the groupby module from itertools.Define a test_list of lists.Define a res variable as an empty list.Use a nested for loop to iterate over the elements of the test_list.For each element, check if it is a list or not.If it is a list, then iterate over each element of the list and append it to the res variable.If it is not a list, append the element directly to the res variable.
Print the res variable as the flattened list.
Python3
from itertools import groupby # Initializing list test_list = [[ 1 , 3 , "gfg" ], [ 4 , 5 ], [ 6 , "best" ]] # Flatten List to individual elements # using groupby() res = [i for j in test_list for i in (j if isinstance (j, list ) else [j])] # printing result print ( "The List after flattening : " + str (res)) #This code is contributed by Rayudu. |
The List after flattening : [1, 3, 'gfg', 4, 5, 6, 'best']
Time Complexity:
The time complexity of the code is O(n), where n is the number of elements in the input list. The nested loop iterates over each element of the input list exactly once.
Space Complexity:
The space complexity of the code is O(n), where n is the number of elements in the input list. The res variable is used to store the flattened list, which can have at most n elements.