Open In App

Python | Convert a nested list into a flat list

Last Updated : 20 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
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]


Previous Article
Next Article

Similar Reads

Flat Panel Display
Flat-Panel Devices are the devices that have less volume, weight, and power consumption compared to Cathode Ray Tube (CRT). Due to the advantages of the Flat-Panel Display, use of CRT decreased. As Flat Panel Devices are light in weights that's why they can be hang on walls and wear them on our wrist as a watch. Flat Panel Display (FPD) allow users
2 min read
Convert an image into jpg format using Pillow in Python
Let us see how to convert an image into jpg format in Python. The size of png is larger when compared to jpg format. We also know that some applications might ask for images of smaller sizes. Hence conversion from png(larger ) to jpg(smaller) is needed. For this task we will be using the Image.convert() method of the Pillow module. Algorithm : Impo
2 min read
Nested list in C++ STL
list in STL is used to represent a linked list in C++. How to create a nested list. We are given n lists, we need to create a list of n lists. Examples: Input : Number of lists: 2 1st list: {1 2} 2nd list: {3 4 5 6} Output : [ [ 1 2 ] [ 3 4 5 6 ] ] Input : Number of lists: 3 1st list : {0 1} 2nd list : {1 2 3} 3rd list : {2 3 4 5} Output : [ [ 0 1
2 min read
Convert String into Binary Sequence
Given a string of character the task is to convert each character of a string into the equivalent binary number. Examples : Input : GFG Output : 1000111 1000110 1000111 Input : geeks Output : 1100111 1100101 1100101 1101011 1110011 The idea is to first calculate the length of the string as n and then run a loop n times. In each iteration store ASCI
5 min read
Convert 1 into X in min steps by multiplying with 2 or 3 or by adding 1
Given an integer X, the task is to convert 1 into X by using the below-given operations: Multiply the number by 2.Multiply the number by 3.Add 1 to the number. The task is to print the minimum number of operations needed to convert 1 into X using these three operations and also print the sequence of operations performed. Examples: Input: X = 5Outpu
10 min read
Convert Image into Sketch
In Python, an image is just a two-dimensional array of integers. So one can do a couple of matrix manipulations using various python modules in order to get some very interesting effects. In order to convert the normal image to a sketch, we will change its original RGB values and assign its RGB values similar to grey, in this way a sketch of the in
3 min read
Convert vowels into upper case character in a given string
Given string str, the task is to convert all the vowels present in the given string to uppercase characters in the given string. Examples: Input: str = “GeeksforGeeks”Output: GEEksfOrGEEksExplanation:Vowels present in the given string are: {'e', 'o'}Replace 'e' to 'E' and 'o' to 'O'.Therefore, the required output is GEEksfOrGEEks. Input: str = “eut
7 min read
Mathematics | Some theorems on Nested Quantifiers
Prerequisite - Predicates and Quantifiers - Set 1, Set 2 Quantifiers are expressions that indicate the scope of the term to which they are attached, here predicates. A predicate is a property the subject of the statement can have. For example, in the statement "the sum of x and y is greater than 5", the predicate 'Q' is- sum is greater than 5, and
4 min read
Convert List to Array in Java
The List interface provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. Now here we are given a List be it any LinkedList or ArrayList of s
3 min read
Converting seconds into days, hours, minutes and seconds
Given an integer n(in seconds).Convert it into days, hours, minutes and seconds.Examples: Input : 369121517Output : 4272 days 5 hours 45 minutes 17 secondsInput : 129600Output : 1 days 12 hours 0 minutes 0 seconds Number of days = ? n / (24 * 3600) ? Number of Hours = ? (n % (24 * 3600)) / 3600 ? Number of Minutes = ? (n % (24 * 3600 * 3600)) / 60
4 min read
Article Tags :
Practice Tags :