Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does return statement with recursion calls hold intermediate values in Python?

Was reviewing some python code related to recursion calls and noticed the return statement looked interesting. How does the recursion work when there is no variable assignment in the return statement for the next recursive call?

As the recursive calls were being made, the intermediate summed values weren't getting stored in an obvious place. The debugger seems to show the list reducing by one each call, but I just don't understand where the intermediate values are getting stored.

Another interesting thing is the debugger seems to iterate one final time through the values once the final call has been made. Using PyCharm, but not sure if that matters.

How does the return statement hold the summed values during the recursive calls in following recursions?

def sum_list(list_of_num):
    if len(list_of_num) == 1:
        return list_of_num[0]
    else:
        return list_of_num[0] + sum_list(list_of_num[1:])

print(sum_list([4,6,7,3,7,3,2]))

2 Answers

The function returns the value to the call higher in the call stack, why do you think it needs a variable, e.g. take a simple recursive call:

def r(n):
    if n == 0:
         return 0
    return 1 + r(n-1)

Then the call stack would look like:

r(3):
    return 1 + r(2)
    r(2):
        return 1 + r(1)
        r(1):
            return 1 + r(0)
            r(0):
                return 0

So when you unwind the call stack you get:

r(3):
    return 1 + r(2)
    r(2):
        return 1 + r(1)
        r(1):
            return 1 + 0
--
r(3):
    return 1 + r(2)
    r(2):
        return 1 + 1
--
r(3):
    return 1 + 2
--
3
like image 124
AChampion Avatar answered May 07 '26 22:05

AChampion


As explained by AChampion if you want to see the same kind of stack trace for your code in Pycharm do few steps .

In Pycharm select

Show return values

Then you can see while debugging each step how the call stack is added and once the operation is done how the values are returned

Call stack return value

like image 26
Hariom Singh Avatar answered May 07 '26 22:05

Hariom Singh