user1159290 user1159290 - 1 year ago 93
Python Question

Get the highest index with a defined value in an array in python

what could be a nice one-liner to get the highest index in a python array whose value is defined (i.e. not None):

f( [None, 1, 5, None, 3, None, None] )

would return:4 (as the "last" defined element is 4. (with value 3))

Sure a search loop would make the job, but it feels non optimal...

Answer Source

Loop over the reversed of the list and return the first valid item's index:

In [70]: next((len(l) - i for i, j in enumerate(l[::-1], 1) if j is not None), 'NOT FOUND')
Out[70]: 4

Note that since you are looping over the reversed array the correct index would be len(l) - i (if we consider the first index as 1).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download