The Wayback Machine - https://web.archive.org/web/20240204104013/https://www.geeksforgeeks.org/python-convert-a-nested-list-into-a-flat-list/
Open In App
Related Articles

Python | Convert a nested list into a flat list

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In this article, we will cover how to Flatten a List of Lists in python. To convert a nested list into a flat list we are going to see some examples.

Example:

Input : l = [1, 2, [3, 4, [5, 6] ], 7, 8, [9, [10] ] ]
Output : l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Input : l = [[['item1', 'item2']], [['item3', 'item4']]] 
Output : l = ['item1', 'item2', 'itm3, 'item4'']

What are nested lists?

A list within a list (or a list within another nested list). The task is to convert a nested list into a single list in python i.e no matter how many levels of nesting is 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 this article, we will cover 5 different approaches to flat a list of lists.

  • Using a nested loop
  • Using a list comprehension
  • Using recursion
  • Using a NumPy module
  • Using a Python in-build sum() method

Example 1: Convert a nested list into a flat list using Nested for Loops

In this example, we will see that we are Iterating the outer list first and then if there is a sub-list then we are iterating the sub-list using for loop. After that, we are appending the element in our new list “flatList” which gives us a flat list of 1 dimensional.

Python3




def flat(lis):
    flatList = []
    # Iterate with outer list
    for element in lis:
        if type(element) is list:
            # Check if type is list than iterate through the sublist
            for item in element:
                flatList.append(item)
        else:
            flatList.append(element)
    return flatList
 
 
lis = [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]]
print('List', lis)
print('Flat List', flat(lis))


Output:

List [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]]
Flat List [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]

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

Example 2: Using a List Comprehension

In this example, we will use list comprehension to  Iterate the list first, and then we are iterating the sub-list using for loop. After that, we are appending the element in our new list “flatList” using a List Comprehension which gives us a flat list of 1 dimensional.

Python3




# Original list
lis = [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]]
 
# iterate through the sublist using List comprehension
flatList = [element for innerList in lis for element in innerList]
 
# printing original list
print('List', lis)
# printing flat list
print('Flat List', flatList)


Output:

List [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]]
Flat List [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]

Example 3: Using recursion

In this example, We are using the recursion method to flat a nested list with multiple levels of nesting.

Python3




# input list
l = [1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]]
 
# output list
output = []
 
# function used for removing nested
# lists in python using recursion
def reemovNestings(l):
    for i in l:
        if type(i) == list:
            reemovNestings(i)
        else:
            output.append(i)
 
 
# Driver code
print('The original list: ', l)
reemovNestings(l)
print('The list after removing nesting: ', output)


Output:

The original list:  [1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]]
The list after removing nesting:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example 4: Using the Pandas module

In this example, we are using a pandas module, pandas have a method called np.concatenate which helps us to flat a nested list. 

Python3




import numpy as np
 
lst = [[11, 33], [22, 55], [11], [77, 88]]
 
new = list(np.concatenate(lst))
 
print(new)


Output:

[11, 33, 22, 55, 11, 77, 88]

Example 5: Using the Python In-build sum() method

In this example, we are using a python In-build sum() method which will give us a flat list.

Python3




lis = [[11, 22, 33, 44], [55, 66, 77], [88, 99]]
 
flatList = sum(lis, [])
 
print('New list', flatList)


Output:

New list [11, 22, 33, 44, 55, 66, 77, 88, 99]

Example 6: Using the Python functools module

The functools module offers ways to use and extend other functions and callable objects without having to totally rewrite them.

Python3




import functools
import operator
 
# Original list
lis = [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]]
 
flatList = functools.reduce(operator.iconcat, lis, [])
 
# printing original list
print('List', lis)
# printing flat list
print('Flat List', flatList)


Output:

List [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]]
Flat List [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]

Example 7: Using the Python itertools module

Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators.

Python3




import itertools
 
# Original list
lis = [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]]
 
flatList = list(itertools.chain(*lis))
 
print("Original List:", lis)
print("Flattened List:", flatList)


Output:

List [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]]
Flat List [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]

Example 8 : Using extend() method

Python3




lis = [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]]
res=[]
for i in lis:
    res.extend(i)
print('List', lis)
print('Flat List', res)


Output

List [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]]
Flat List [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!


Last Updated : 20 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads