def number_sum(numbers): total = 0 for n in numbers: if isinstance(n, int): total += n elif isinstance(n, list): total += number_sum(n) return total
In order to find the sum of a list, iterate over each item in the list:
Do you understand how this code works? This little piece of code applies a concept that makes freshman CS students shudder: recursion. A recursive function is a function that calls itself.
It is a natural fit to use recursion here because our input list has a recursive structure.
Our input list contains numbers and lists.
Each of those lists contains numbers and lists.
Each of those lists contains numbers and lists.
In that sense, the structure of the lists at each level is the same as every other level.
If we can call number_sum
on our input list, surely it makes sense to call it on its sublists.
After you've let that sink in, click here for some final thoughts.