Indentifying the LAST occurrence of an item in a list
Tim Williams
tim at tdw.net
Wed Apr 4 13:55:20 EDT 2007
On 4 Apr 2007 08:58:49 -0700, tkpmep at hotmail.com <tkpmep at hotmail.com> wrote:
> 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?
Simpler ? That's subjective. :)
You definitely need to search/iterate a reversed list, or start from
the far end of a non-reversed list.
For fun only.
>>> t = [0,1,2,3,0]
>>> def place(t,i):
... for x,y in zip(t,range(len(t)))[::-1]:
... if x == i:
... return y
...
>>> place(t,3)
3
>>> place(t,0)
4
More information about the Python-list
mailing list