Reputation: 17
I need to write a python function that will count all the elements in a list, including those elements in a nested list.
Example, len()
is built in function, at_len()
is the function I want to create:
len( [1, 2] ) ---> 2
at_len( [1, 2] ) ---> 2
len( [ [1, 2], 3 ] ) ---> 2
at_len( [ [1, 2], 3 ] ) ---> 3
len( [1, 2, 'three', [1, 2, 3, ['a', 'b'] ], 5] ) --> 5
at_len( [1, 2, 'three', [1, 2, 3, ['a', 'b'] ], 5] ) --> 9
I need to be able to count those elements that are in nested lists. This is the code that I have, as well as the output I am getting.
def at_len(element_list):
count = 0
for each_item in element_list:
if isinstance(each_item, list):
at_len(each_item)
else:
count = count + 1
print(count)
output:
at_len(['hello',1,2,'three',[1,'two',3]]) --> 3, 4 (should be 7)
at_len([1,2,[1,2,3]]) --> 3, 2 (should be 5)
I think I am close, but for some reason it prints out two counts instead of having them added together to get the correct total.
Upvotes: 1
Views: 3134
Reputation: 31319
The whole function is really nothing more than:
def at_len(xs):
return sum(at_len(x) for x in xs) if isinstance(xs, list) else 1
Or if you need it to not just work for lists:
from typing import Iterable
def at_len(xs):
return sum(at_len(x) for x in xs) if isinstance(xs, Iterable) else 1
Upvotes: 0
Reputation: 23827
Replace at_len(each_item)
by count += at_len(each_item)
and then return count
(instead of printing).
It's printing twice because of the recursive call. The print command is within the function. Also notice that total is given a value but never used. Instead do it as
def at_len(element_list):
count = 0
for each_item in element_list:
if isinstance(each_item, list):
count += at_len(each_item)
else:
count += 1
return count
then just call it as:
print(at_len(yourlist))
Upvotes: 4