I am learning tail recursion and don't understand the flow of this example.
I am using VSCode debugger and don't understand why when the program reaches return[f(arg), *result]
it goes to result = my_map(f, rest)
line and arg
becomes 2
(attached picture VSCode Debugger - step I don't understand).
def my_map(f, iterable):
try:
arg, *rest = iterable
except ValueError:
return []
result = my_map(f, rest)
return[f(arg), *result]
print(my_map(lambda x: x+10, [1,2,3]))
I am not used to the unpack operator (*) so maybe I am missing something there.
Since arg
was 3
and result
was []
, I was just expecting the return
to return a list like [3,[]]
.
Title EDITED: it is not tail recursion since the recursion isn't the last thing the function does.- Thanks > https://stackoverflow.com/users/1491895/barmar
EDITED: more explanation about what I don't understand: First, I get everything until result becomes an empty list. looping through try-except block Then, we get into return [f(arg),*result] There is where I don't understand why the execution (seeing it from the debugger) goes back to the previous line (result). So if someone could explain me what is happening from that point on...
To understand the flow I had 1st to watch this ideal video about recursion https://www.youtube.com/watch?v=AfBqVVKg4GE Then I understood that it was not a good example to understand recursion at all...
So based on that, I did the map of the call stack status in the same fashion it is done in the video. See picture: Call stack status
Hope it helps