1

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?

user80551
  • 1,134
  • 2
  • 15
  • 26
  • possible duplicate of [Equivelant to rindex for lists in Python](http://stackoverflow.com/questions/9836425/equivelant-to-rindex-for-lists-in-python) – alecxe Apr 01 '14 at 18:01
  • Yeah, its a duplicate of http://stackoverflow.com/questions/6890170/python-how-to-find-last-occurrence-in-a-list-in-python , could someone close it? – user80551 Apr 01 '14 at 18:04

2 Answers2

1

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.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
0

If you don't care about list order being preserved, you could always use lst.reverse() before lst.index(1).

Documentation is on the official site

Daniel Kotin
  • 326
  • 2
  • 8