[Solved] How do lists work in python recursion and why does int + list in recursion not fail?


list_sum_recursive doesn’t return a list; it returns the sum of the values in its argument:

list_sum_recursive([]) == 0

list_sum_rescursive([1]) == 1 + list_sum_recursive([])
                         == 1 + 0
                         == 1

list_sum_rescursive([1, 2]) == 1 + list_sum_recursive([2])
                            == 1 + (2 + list_sum_recursive([]))
                            == 1 + (2 + 0)
                            == 1 + 2
                            == 3

If you were to provide type hints for this function, it might look something like

def list_sum_recursive(input_list: List[int]) -> int

Not just any list can be passed, as it is assumed that input_list[0] will be something you can add to (ultimately) 0.

1

solved How do lists work in python recursion and why does int + list in recursion not fail?