Recursion#

A useful programming technique is recursion. That is, a function calls itself until some stopping criterion is satisfied.

To illustrate this approach let’s have a list. Each item either is an integer or a list again. If it is a list, then each item of this list is an integer or another list, and so on. The task is to calculate the sum of all integers. This can’t be solved by nested for loops, because we do not know the depth of the list nesting in advance.

def sum_list(l):
    ''' Sum up list items recursively. '''
    
    current_sum = 0
    
    for k in l:
        if type(k) == int:
            current_sum += k
        else:
            current_sum += sum_list(k)
    
    return current_sum


a = [[1, 2, 3], 4, [5, [6, 7], 8]]

print(sum_list(a))            
36