I get the data in the following format:
[-2, -2, 0, 0, 0, 0, 0]
[-2, 20, -1, 0, 3, 0, 0]
each line representing a different input. Lists can be longer than 7 items. I need to return the index position of the last nonzero element, so:
[-2, -2, 0, 0, 0, 0, 0]
>>> 1
[-2, 20, -1, 0, 3, 0, 0]
>>> 4
This code does this most of the time:
def getIndex(list):
for element in reversed(list):
if element != 0:
return list.index(element)
However, it does not work when there are two identical numbers, as in the first example above, which returns 0because it -2is in both the 0th and the first positions of the list.
So, how to get the index of the last non-zero list item, even if there are items with the same value?