Reputation: 3171
In a learning exercise we were asked to traverse a multi-dimensional list and print all of its values in a single function/for loop.
My brain got stuck on the basics of how a recursive function should work, through some online examples I came up with what I tought was the answer, but it stops at the first list with values it finds.
What was the mistake of my train of tought here?
def walk(l):
for v in l:
if type(v) is list:
return walk(v)
else:
print(v)
l = [
[1,2,3],
[4,5,6],
[7,8,9]
]
walk(l)
>>1
>>2
>>3
Upvotes: 2
Views: 2955
Reputation: 215137
Remove the return statement, as it stops you from going into the next iteration in the for loop (when you call walk(l), it checks the first sub list and finds that it is a list and then encounter return, this stops the execution of the current function and so it will not go to the next iteration any more but will only execute walk([1,2,3]) and print out the results):
def walk(l):
for v in l:
if type(v) is list:
walk(v)
else:
print(v)
walk(l)
1
2
3
4
5
6
7
8
9
Upvotes: 4