solved this task:
Turn a nested list into a flat list Imagine that we have a list of integers with unlimited nesting. That is, our list can consist of lists, which can also have lists inside them. Your task is to turn it all into a linear list with the function flatten
flatten([1, [2, 3, [4]], 5]) => [1, 2, 3, 4, 5]
flatten([1, [2, 3], [[2], 5], 6]) => [1, 2, 3, 2, 5, 6]
flatten([[[[9]], [1, 2], [[8]]) => [9, 1, 2, 8]
The for loop is not working correctly :/
Why is list type ignored in this case?
def flatten(sp: list, b=[]) -> list:
if len(sp) == 0:
print(b)
for i in sp:
if type(i) == list:
flatten(i)
elif type(i) == int:
b.append(i)
sp.remove(i)
And that doesn't happen in this?
for i in [1, [2, 3, [4]], 5]:
if type(i) == list:
print('YES')
In the end, the task was solved as follows:
def flatten(lst, new_lst = []):
for i in lst:
if isinstance(i, list):
flatten(i)
else:
new_lst.append(i)
return new_lst
Please explain why this is so