Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to start counter when a condition is met

If I have a list
x=[0.0,0.0,2.0,3.0,0.0,2.0]
And I basically want to count the amount of items in the list but only start after the leading zeroes, how would I do that? Keep in mind that I want to count the zero in the middle of the list but not the ones at the beginning. Thanks

Edit:
I’ve tried this:

n=0
for i in x:
    while i==0.0:
       break
    if i!=0.0:
       n=n+1

But it didn’t get 4, which is the output I want as I want to include 2.0,3.0,0.0,2.0 only

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can simply wrap your counter code in a conditional, with something like this:

x=[0.0,0.0,2.0,3.0,0.0,2.0]
start_counting = False
item_count = 0

for i in x:
    if i != 0.0:
        start_counting = True
    if start_counting:
        item_count += 1

item_count will now have the amount of items in the list without the starting 0.0s

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading