I am trying to calculate the number of elements in a list including the elements in the lists' list.
Here is my code
my_list = [1,[2,3],[4,5,6]]
sum = 0
for x in my_list:
for i in mylist:
sum = sum+1
print(sum)
I am trying to calculate the number of elements in a list including the elements in the lists' list.
Here is my code
my_list = [1,[2,3],[4,5,6]]
sum = 0
for x in my_list:
for i in mylist:
sum = sum+1
print(sum)
Here you go...you need to check the data types:
my_list = [1,[2,3],[4,5,6]]
sum = 0
for x in my_list:
if type(x) == list:
sum += len(x)
else:
sum += 1
print(sum)
my_list = [1,[2,3],[4,5,6]]
print(sum(len(x) if isinstance(x, list) else 1 for x in my_list))
Biggest thing to note is that your my_list contains values of different types. e.g, (list, int). Therefore you need to do type checking.
To handle nested lists you will need to create a recursive function.
Example using python 3.6+
def sum_mylist(my_list: list) -> int:
total = 0
for i in my_list:
if isinstance(i, list):
total += sum_mylist(i)
if isinstance(i, int):
total += i
return total
def main():
my_list = [1,[2,3,4], 5, [4,5,6], [1, [2,3,4]]]
total = sum_mylist(my_list)
print(total) // prints 40
main()
UPDATED as per @ShadowRanger comments.