0

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]]
1
  • Its less about the the empty array that's being returned and more about it not calling itself anymore. Once reverse stops getting called, you start unwinding the stack to the initial call. Commented Feb 6, 2019 at 10:50

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that helped me understand the code. So basically, the function will recognize if I call it with another parameter in a recursion and then it will be able to return it? I just tried doing it with other datatypes as well and it seems to be only working with strings and lists in this particular case.
You can return any datatype that can be joined (+ operator) with a list. Since, string is a list of characters, so it works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.