Indentifying the LAST occurrence of an item in a list

John Machin sjmachin at lexicon.net
Thu Apr 5 20:37:47 EDT 2007


On Apr 6, 4:55 am, "mkPyVS" <mikemine... at hotmail.com> wrote:
> Not sure below is better but it hacks at larger chunks (excuse the 10
> second coding)
> m = [2,9,1,5,6,3,1,1,9,2]
> f = 1
> temp = m

Overwritten 3 statements later

> location = m.index(f)
> gloc = location
> temp = m[location:]
> while 1:
>    print(temp)
>    try:
>       location = temp.index(f) + 1
>       gloc += location
>    except:
>       break
>    temp = temp[location:]

Each time you do that you are copying a chunk of the original list.
This could be expensive on a large list. Reminds me of the old joke
about how many marines it takes to paint the barracks: 200 to
oscillate the barracks, one to hold the brush steady. You don't need
to do that. Here's a clue:

| >>> help(list.index)
Help on method_descriptor:

index(...)
    L.index(value, [start, [stop]]) -> integer -- return first index
of value

I look forward to your next version.

Cheers,
John




More information about the Python-list mailing list