MrSebo
MrSebo

Reputation: 49

Why does this recursive Python function return the reversed object as a list?

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

Answers (1)

dvlper
dvlper

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

Related Questions