Skip to content
Advertisement

How to get items from a list but only after 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.

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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement