Recursion means 'defining something depending on itself'.(1)Although it can be equally written by while loops, it is more convenient and brief to use it. Nonetheless, it is a bit hard to understand at first. So we always trace it in order to understand.
We starts from trace the code sum_list. Let's take a look at the codes below.
def sum_list(L):
’’’
(arbitrarily nested list of int or int) -> int
Return the sum of all ints in L.
>>> sum_list([1, [2, 3], [4, 5, [6, 7], 8]])
36
’’’
if isinstance(L, list):
return sum([sum_list(x) for x in L])
else:
return L
When we trace the code, we use some examples from easy to complicated. And we apply the result of the former examples which are easier to more complicated examples, which reduces work during tracing period. I think taking examples contributes to understand abstract codes.
(1) is from http://openbookproject.net/thinkcs/python/english3e/recursion.html
The codes above is from the handout on csc148 website.