I need to write a recursive function that returns a list from original list where each element consists of elements in that level. For example [1, [2, [3], [[4], 3], 2], 1, []]
for that list the result should be [[1, 1], [2, 2], [3, 3], [4]]
(elements 1, 1 are on level 1, elements 2, 2 on level 2 and etc.). And another example would be [8, [6, 7, [-1], [4, [[10]]], 2], 1]
turns to [[8, 1], [6, 7, 2], [-1, 4], [], [10]]
. I've tried to go through every element and when it's not a list, add the element to result. Else I call out the function again until I reach just a element again. But the problem is that it just adds all the elements to result. I'm stuck and don't really know how to continue.
def levels(x, level = 0, result = []):
for element in x:
if type(element) is not list:
result.append(element)
else:
levels(element, level + 1, result)
return result
print(levels([1, [2, [3], [[4], 3], 2], 1, []]))
print(levels([8, [6, 7, [-1], [4, [[10]]], 2], 1]))
My result:
[1, 2, 3, 4, 3, 2, 1]
[1, 2, 3, 4, 3, 2, 1, 8, 6, 7, -1, 4, 10, 2, 1]
What it should be:
[[1, 1], [2, 2], [3, 3], [4]]
[[8, 1], [6, 7, 2], [-1, 4], [], [10]]
Any help is greatly appreciated.