Search code examples
pythonrecursion

RecursionError: maximum recursion depth exceeded while calling a Python object. python error


could someone help please, i do not know why i get this error:

def sum_list(the_list):
    if not the_list:
        return 0
    else:
        mid = len(the_list) // 2
        return sum_list(the_list[:mid]) + sum_list(the_list[mid:])


print(sum_list([10, 20, 30]))

Solution

  • if the_list is of length 1 (which will happen at some stage in your recursive calls) you will end up in an infinite recursion... (mid will be 0).

    you need to address that as a second base case:

    def sum_list(the_list):
        if not the_list:
            return 0
        if len(the_list) == 1:
            return the_list[0]
        else:
            mid = len(the_list) // 2
            return sum_list(the_list[:mid]) + sum_list(the_list[mid:])
    

    i assume this is an exercise in recursion. python offers sum to do that efficiently.