Flatten List Of Lists In Python

In this tutorial, I will show you a program of how to flatten list of lists in python. So without wasting any further time let’s get started.

Input : [1,2,3,[4,5],[[6],7]]

Output : [1,2,3,4,5,6,7]

Program To Flatten list of lists in python

In this code example, we have used the recursion technique of programming to flatten a list. Here is the algorithm.

  • We first defined an empty list to store the final flatten list.
  • Then we iterate through each element of the input list.
  • On each iteration, We check if the current element is an instance of the list then, we recursively call the function on it.
  •  Else, we append the element inside the result list.
def flatten(lis):
    result = [] # list to store the final flatten list
    for i in list: # iterate through the input list
        if isinstance(i,list): # check if current element type is list
            result += flatten(i) # if yes recursively call the function
            result.append(i) # else append the element to the result
    return result # return the flatten list to the caller

d = [1,2,3,[4,5],[[6],7]] # input list
f = flatten(d) # call the function
print(d) # print on console

Here is the output of the above code.

Output :

Output of the program to Flatten List Of Lists In Python

Also read about how to take average of a list in python.

Leave a Reply