0

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)

Zoe
  • 27,060
  • 21
  • 118
  • 148
Seymour
  • 27
  • 3

3 Answers3

1

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)
user212514
  • 3,110
  • 1
  • 15
  • 11
1
my_list = [1,[2,3],[4,5,6]]
print(sum(len(x) if isinstance(x, list) else 1 for x in my_list))
Joan Lara
  • 1,362
  • 8
  • 15
1

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.

Mike Hawes
  • 555
  • 5
  • 8
  • will only do 1 level of nesting – Patrick Artner May 08 '19 at 19:18
  • This is on the right track, though the OP's comments indicate they want to handle arbitrarily nested lists (so the outer `list` might contain one or more inner `list`s, which themselves contain one or more inner `list`s, ad infinitum). You'd need to recurse to handle that (replacing your call to `sum` with a recursive call to `sum_mylist`). Side-note: You usually want `isinstance(i, list)`, and even if you insist on exact types, the correct check in that case is `type(i) is list`, not `type(i) == list` (classes are singletons, so `is` is the correct test to stick to cheap identity tests). – ShadowRanger May 08 '19 at 19:20
  • Updated @ShadowRanger – Mike Hawes May 08 '19 at 19:41