Issue
my_list = [6, 36, [54, 5], 13, [3, 5], ["b", 2]]
# do something
...
print(len(new_list))
>>> 9
I have a nested list in Python. How should I go about reaching the number of elements of this list?
Solution
Assuming a classical python list, this can typically be solved by recursion:
my_list = [6,36,[54,5],13,[ 3,5], ["b",2]]
def nelem(l, n=0):
if isinstance(l, list):
return sum(nelem(e) for e in l)
else:
return 1
nelem(my_list)
# 9
collecting the elements:
my_list = [6,36,[54,5],13,[ 3,5], ["b",2]]
def nelem(l, n=0, out=None):
if isinstance(l, list):
return sum(nelem(e, out=out) for e in l)
else:
if out is not None:
out.append(l)
return 1
x = []
n = nelem(my_list, out=x)
print(n)
# 9
print(x)
# [6, 36, 54, 5, 13, 3, 5, 'b', 2]
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.