Nov-22-2020, 12:44 PM
def sumtree(l): tot = 0 for x in l: if not isinstance(x, list): tot += x print(tot) else: tot += sumtree(x) print('xxx') return tot o = [1, [2, [3, 4], 5], 6, [7, 8]]I don't understand how this works. It sums the items in the nested nested lists.
I've typed this interactively:
>>> type(o[0])
<class 'int'>
>>> type(o[1])
<class 'list'>
>>> type(o[2])
<class 'int'>
>>> type(o[3])
<class 'list'>
>>> o[1]
[2, [3, 4], 5]
>>> o[0]
1
>>> o[1]
[2, [3, 4], 5]
>>> o[2]
6
>>> o[3]
[7, 8]
if I run it it gives this:
1
2
3
7
xxx
14
xxx
21
7
15
xxx
36
1
3
6
10
10
The for loop seems to step over the first item in each nested list, but why does it do that? It's probably really easy, I've been staring at it for hours. Any help or explanation would be greatly appreciated.