Indentifying the LAST occurrence of an item in a list

John Machin sjmachin at lexicon.net
Wed Apr 4 23:45:22 CEST 2007


On Apr 5, 1:58 am, tkp... 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?
>

If you need to do this for several possible items in the same list, it
may be worthwhile to build a dictionary containing all the answers:

| >>> seq = ['foo', 'bar', 'foo', 'bar', 'zot', 'foo']
| >>> rindex = dict((elt, inx) for inx, elt in enumerate(seq))
| >>> rindex
| {'zot': 4, 'foo': 5, 'bar': 3}

If you tell us what is the higher-level problem, we may be able to
help you further. In other words, if lists did have a rindex method,
what would you be using it to do? Are you constrained to use a list,
or would another data structure be better?

HTH,

John




More information about the Python-list mailing list