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?
If you are actually using just single letters like shown in your example, then
str.rindexwould work handily. This raises aValueErrorif there is no such item, the same error class aslist.indexwould raise. Demo:For the more general case you could use
list.indexon the reversed list:The slicing here creates a copy of the entire list. That’s fine for short lists, but for the case where
liis very large, efficiency can be better with a lazy approach:One-liner version: