In python, if I have a list say [2,1,1,3,5]
, then is it possible to get
[2,1,1,3,5].index(1)
as 2
i.e first match starting from the higher end instead of the lower?
In python, if I have a list say [2,1,1,3,5]
, then is it possible to get
[2,1,1,3,5].index(1)
as 2
i.e first match starting from the higher end instead of the lower?
Can't say I've ever needed to do this, but you could always hack it with:
lst = [2,1,1]
reverseindex = len(lst)-1 - lst[::-1].index(1)
Note that if you had a STRING, you could do:
string = "21135"
reverseindex = string.rindex(1)
# reverseindex == 2
But lists don't have this function.
If you don't care about list order being preserved, you could always use lst.reverse()
before lst.index(1)
.