Indentifying the LAST occurrence of an item in a list

7stud bbxx789_05ss at yahoo.com
Wed Apr 4 13:27:28 EDT 2007


On Apr 4, 11:20 am, "7stud" <bbxx789_0... at yahoo.com> wrote:
> On Apr 4, 10:55 am, "Terry Reedy" <tjre... at udel.edu> wrote:
>
> > <tkp... 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?
>
> How about:
>
> l = [1, 2, 1, 3, 1, 5]
> target = 1
> for index, val in enumerate(l):
>     if val==1:
>         lastIndexOf = index
>
> print lastIndexOf

Nahh.  Horrible solution.  You should start at the end of the list.




More information about the Python-list mailing list