Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the last occurrence of an item in a Python list

Say I have this list:

li = ["a", "b", "a", "c", "x", "d", "a", "6"] 

As far as help showed me, there is not a builtin function that returns the last occurrence of a string (like the reverse of index). So basically, how can I find the last occurrence of "a" in the given list?

like image 764
Shaokan Avatar asked Jul 31 '11 14:07

Shaokan


People also ask

How do I get the last element in a list?

Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want last element in list, use -1 as index.

How do you find the last occurrence of a string in Python?

The rfind() method finds the last occurrence of the specified value. The rfind() method returns -1 if the value is not found. The rfind() method is almost the same as the rindex() method.

How do you find the first occurrence of a value in a list in Python?

Python – Find Index or Position of Element in a List. To find index of the first occurrence of an element in a given Python List, you can use index() method of List class with the element passed as argument. The index() method returns an integer that represents the index of first match of specified element in the List.

How do you find the first occurrence of an item in a list?

index() As list. index() returns the index of first occurrence of an item in list. So, to find other occurrences of item in list, we will call list.


1 Answers

If you are actually using just single letters like shown in your example, then str.rindex would work handily. This raises a ValueError if there is no such item, the same error class as list.index would raise. Demo:

>>> li = ["a", "b", "a", "c", "x", "d", "a", "6"] >>> ''.join(li).rindex('a') 6 

For the more general case you could use list.index on the reversed list:

>>> len(li) - 1 - li[::-1].index('a') 6 

The slicing here creates a copy of the entire list. That's fine for short lists, but for the case where li is very large, efficiency can be better with a lazy approach:

def list_rindex(li, x):     for i in reversed(range(len(li))):         if li[i] == x:             return i     raise ValueError("{} is not in list".format(x)) 

One-liner version:

next(i for i in reversed(range(len(li))) if li[i] == 'a') 
like image 90
wim Avatar answered Oct 22 '22 15:10

wim