0

I have this problem, I want to count how many integers in a list AND sub-lists.

I have this code but doesn't seem to be working:

x = [[1, 3], [0], [2, -4]]

count = 0pos = 0

for i in x[pos]:count = count + len(x[pos])pos = pos + 1

    print(count)

Expected 5 because there are 5 elements.

  • It would be helpful if you explained if there are expectations on the input. For example, this is also a "nested list", could you have input like `[[1, 2, [3,4,[5]]], 2, [1, [2, 3]]]`? – Mark Mar 29 '22 at 05:01
  • P.S. the question linked as a dupe *might* be helpful if you have complex nested lists. If your input is always a simple list of lists, it's over-kill. I'm sorry somebody closed it with such an unhelpful dupe. If this is the case, consider just taking the sum of lengths: `total = sum(len(l) for l in x)` – Mark Mar 29 '22 at 05:07

1 Answers1

0

I've edited your code to the following:

x = [[1, 3], [0], [2, -4]]

count = 0

for arr in x:
    for element in arr:
        count +=1
print(count)
anosha_rehan
  • 1,522
  • 10
  • 17