28
loading...
This website collects cookies to deliver better user experience
l = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
[1, 'a', 'cat', 2, 3, 'dog', 4, 5]
from typing import List
l = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
flat_list2 = []
def lookInside(l): # Takes the list type element
for x in l: # For each sub-element of it
if type(x) is not list: # If the sub-element is not list,
flat_list2.append(x) # Then add it to flat_list
else:
lookInside(x) # Else, look inside of it again
# WE ARE STARTING HERE !!!
def makeFlat(l): # Getting the list
for e in l: # Checking the elements of the list
if type(e) is list: # If element's type is list then
lookInside(e) # send that element to lookInside function
else:
flat_list2.append(e) # Else, (if it is not list) append it to our new flat_list
makeFlat(l) # Function call, the complex list has been given to function
print(flat_list2) # Printing the flatten list
[ 1, [2], [[3]] ] ==> Our function takes 1 as a normal element
[ [2], [[3]] ] ==> Then for [2] we are going to our recursive function, this function looks inside of it then sees that "2" is not list, then add it to new list
[ [[3]] ] ==> Then for [[3]] we are going to our recursive function, function looks at it and says that [3] is a list then send it to itself again just as [3]. After that (like [2]) it looks inside of [3] and sees that 3 is not list then add it into new list.