Indentifying the LAST occurrence of an item in a list
Terry Reedy
tjreedy at udel.edu
Wed Apr 4 12:55:30 EDT 2007
<tkpmep at hotmail.com> wrote in message
news:1175702329.330032.250750 at w1g2000hsg.googlegroups.com...
| For any list x, x.index(item) returns the index of the FIRST
| occurrence of the item in x. Is there a simple way to identify the
| LAST occurrence of an item in a list? My solution feels complex -
| reverse the list, look for the first occurence of the item in the
| reversed list, and then subtract its index from the length of the list
| - 1, i.e.
|
| LastOcc = len(x) - 1 - x[::-1].index(item)
|
| Is there a simpler solution?
Unless I wanted the list reversed, I would simply iterate backwards,
parhaps in a utility function.
def rindex(lis, item):
for i in range(len(lis)-1, -1, -1):
if item == lis[i]:
return i
else:
raise ValueError("rindex(lis, item): item not in lis")
t=[0,1,2,3,0]
print rindex(t,3)
print rindex(t,0)
print rindex(t,4)
# prints 3, 4, and traceback
Terry Jan Reedy
More information about the Python-list
mailing list