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:



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 | Ways to flatten a 2D list
Given a 2D list, Write a Python program to convert the given list into a flattened list. Method #1: Using chain.iterable() C/C++ Code # 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 (
5 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
Practice Tags :
three90RightbarBannerImg