Reputation: 49
I have a working code and it is fully functional. However, I do not understand WHY it works the way it does and it would be most awesome if you guys could explain it to me.
What I understand is that each recursion will be in the stack until the function is terminated, so the results of each calculation are kept. What I don't understand is why a simple return [] will actually return the result of each recursion.
def reverse(li):
if not li:
return []
else:
return reverse(li[1:]) + [li[0]]
Upvotes: 0
Views: 44
Reputation: 472
Concept of recursion has a case called termination condition; which determines when to stop recursion. When this condition is met, the function will no longer call itself. In you case, you return a list when termination condition is met.
As for why returning a list is important, because you are appending another list [li[0]]
to the result of the reverse()
function.
Upvotes: 1