I came across this function:
def count_list(l):
count = 0
for e in l:
if isinstance(e, list):
count = count + 1 + count_list(e)
return count
I couldn't understand it especially the for e in 1
and isinstance(e, list)
, wonder if any pro can explain? Just started learning function, list
, in
and isinstance
Let's read it:
# define the method count_list that take one argument l (lower L)
def count_list(l):
# define count to be a int with value 0
count = 0
# for each item e in l (we supose that l can be itered)
for e in l:
# if e is a list
if isinstance(e, list):
# add one to count and the result of count_list called on e (recursive call)
count = count + 1 + count_list(e)
return count
Remarks:
e
is not a list count
doesn't change. This method increment count
by one only when a list is found inside l
.l
. For each list it meet, it add 1+number of list in that list
using recursive calls.Example:
Here a representation of the content of l
:
What happen when we call count_list(l)
:
count_list
is called with the parameter l
(call 1).l
are iterated.ListA
is a list. count
(in call 1) is incremented by 1 and the result of the call to count_list
with the parameter ListA
.count_list
is called with the parameter ListA
(call 2).
ListA
are iterated.ListB
is a list. count
(in call 2) is incremented by 1 and the result of the call to count_list
with the parameter ListB
.
count_list
is called with the parameter ListB
(call 3).ListB
are iterated.0
is returned (call 3)count
(in call 2) value is the result of 0+1+0
. It's 1
.ListC
is a list. count
(in call 2) is incremented by 1 and the result of the call to count_list
with the parameter ListC
.
count_list
is called with the parameter ListC
(call 4).ListC
are iterated.0
is returned (call 4)count
(in call 2) value is the result of 1+1+0
. It's 2
.ListA
.2
is returned (call 2)count
(in call 1) value is the result of 0+1+2
. It's 3
.l
.3
is returned (call 1)