For Rindex for lists in Python

Is there an effective way to find the last matching item in a list? When working with strings, you can find the last element with rindex:

>>> a="GEORGE" >>> a.rindex("G") 4 

... But this list does not exist for lists:

  >>> a=[ "hello", "hello", "Hi." ] >>> a.rindex("hello") Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'rindex' 

Is there a way to get this without creating a big loop? I would prefer not to use the inverse method if it can be avoided, since the order is important, and I also need to do some extra math to find out where the object / was / was. It seems wasteful.

Edit:

To clarify, I need the index number of this item.

+6
python list
Mar 23 2018-12-12T00:
source share
4 answers

What about:

 len(a) - a[-1::-1].index("hello") - 1 

Change (enable function as suggested):

 def listRightIndex(alist, value): return len(alist) - alist[-1::-1].index(value) -1 
+12
Mar 23 2018-12-12T00:
source share

This should work:

 for index, item in enumerate(reversed(a)): if item == "hello": print len(a) - index - 1 break 
+5
Mar 23 '12 at 9:24
source share

I wrote a simple Python function, and here it is:

 def list_rindex(lst, item): """ Find first place item occurs in list, but starting at end of list. Return index of item in list, or -1 if item not found in the list. """ i_max = len(lst) i_limit = -i_max i = -1 while i > i_limit: if lst[i] == item: return i_max + i i -= 1 return -1 

But while I tested it, EwyynTomato posted the best answer. Use the slicing tool to expand the list and use the .index() method.

+3
Mar 23 '12 at 9:40
source share

Supports start :

 def rindex(lst, val, start=None): if start is None: start = len(lst)-1 for i in xrange(start,-1,-1): if lst[i] == val: return i 
0
Jul 09 '12 at 1:14
source share



All Articles