Search code examples
pythonlistsumcounting

How do I count the last elements in a list after a certain element?


I have a python list containing zeros and ones like this:

a = [1.0 1.0 0.0 0.0 1.0 0.0 1.0 0.0 0.0]

I know how to count the ones and zeros in this, but what I can't manage to figure out is how to count the last zeros after the last 1.0 in that list. In this case the solution would be "2". I would like to have a simple code which I can use for this problem in order to put it in a loop.

I hope someone can help me with that. Thank you!


Solution

  • Try this:

    a = [1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0]
    a[::-1].index(1)
    

    You reverse the list, and take the index of the first 1.