Open In App

Python – Flatten List to individual elements

Last Updated : 21 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn How to Flatten a List of lists through list comprehension in Python.

Sometimes, while working with a Python list, we can have a problem in which we need to perform flattening 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.

Example:

Input: [[1,3, "geeks"], [4,5], [6, "best"]]
Output: [1, 3, 'geeks', 4, 5, 6, 'best']
Explaination: Flattening convert a mixed list to a flattened one.

How to Flatten the List to Individual Elements in Python

Below are the methods that we will cover in How to Flatten a List of Lists in Python:

1. Using List Comprehension to Flatten a List of Lists

Here, we are using list comprehension to flatten the list from 2D to 1D.

Python3




res = [i for row in [[1,3,"geeks"], [4,5],
                     [6,"best"]] for i in row]
print(res)


Output:

[1, 3, 'geeks', 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 

2. Using sum() Function to Flatten a List of Lists

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

3. Using for Loop to Flatten a List of Lists

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, 'geeks'], 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, ‘geeks’, 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.

4. Using flatten() method to Flatten a List of Lists

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']

5. Using chain() with isinstance() to Flatten a List of Lists

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, 'geeks'], 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, ‘geeks’, 67.4, 5, ‘best’]

Time complexity: O(n)
Auxiliary Space: O(n)

6. Using reduce() Function to Flatten a List of Lists

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


Output:

The List after Flattening : [1, 3, 'gfg', 4, 5, 6, 'best']

Time complexity: O(n)
Auxiliary Space: O(n)

7. Using groupby to Flatten a List of Lists

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.


Output:

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.

8. Using itertools.chain.from_iterable() to Flatten a List of Lists

In this example the below code uses the itertools.chain.from_iterable() method to flatten a nested list.

Let’s break down the code and explain : The below code uses `itertools.chain.from_iterable()` to flatten a nested list (`nested_list`) into a single list (`flattened_list`), and then prints the result.

Python3




from itertools import chain
 
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flattened_list = list(chain.from_iterable(nested_list))
 
print(flattened_list)


Output :

[1, 2, 3, 4, 5, 6, 7, 8]

Time complexity: O(n)
Auxiliary Space: O(n)

9. Using recursion to Flatten a List of Lists

In this example the below code defines a function flatten_list that takes a nested list as input and returns a flattened list with individual elements. The flattening is achieved using recursion.

Python3




def flatten_list(lst):
    flat_list = []
    for item in lst:
        if isinstance(item, list):
            flat_list.extend(flatten_list(item))
        else:
            flat_list.append(item)
    return flat_list
 
nested_list = [[1, 2, 3], [4, [5, 6]], [7, 8]]
flattened_list = flatten_list(nested_list)
 
print(flattened_list)


Output :

[1, 2, 3, 4, 5, 6, 7, 8]

Time complexity: O(n)
Auxiliary Space: O(n)

We have covered 9 total ways to flatten a list of lists. List flattening in Python is used to convert a list of nested lists into a single list. You can use any of the above method to flatten your list according to your requirements.

Similar Reads:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads