Convert a nested list into a flat list in Python

PythonServer Side ProgrammingProgramming

A nested list is a list whose elements are lists themselves. If we have a python data container which is a nested list, we may sometimes need to convert it into a flattened list so that each element can be processed further.

Even the inner elements can also be nested themselves. And there can be many layers of nesting. So we will approach this problem with recursion. We will keep checking if the element is nested and then keep going applying the function again and again until the element is no longer a list. Once it is found that element is not a list, we will append it to a new list which will hold all the non-nested elements of the list.

Example

 Live Demo

listA = [[43, [0]],12, 19, [13,[8, 8]], 21 ]
print('Given nested list: \n', listA)
# Flat List
res = []
# function
def flatlist(l):
   for x in l:
      if type(x) == list:
         flatlist(x)
      else:
         res.append(x)
flatlist(listA)
print('Flattened List created: \n', res)

Output

Running the above code gives us the following result −

Given nested list:
[[43, [0]], 12, 19, [13, [8, 8]], 21]
Flattened List created:
[43, 0, 12, 19, 13, 8, 8, 21]
raja
Published on 20-May-2020 14:09:29
Advertisements