finding the last occurrence of an item in a list python

efc1 picture efc1 · Dec 23, 2015 · Viewed 7.1k times · Source

I wish to find the last occurrence of an item 'x' in sequence 's', or to return None if there is none and the position of the first item is equal to 0

This is what I currently have:

def PositionLast (x,s):

    count = len(s)+1
    for i in s:
        count -= 1
        if i == x:
           return count
    for i in s:
        if i != x:
           return None

When I try:

>>>PositionLast (5, [2,5,2,3,5])
>>> 4

This is the correct answer. However when I change 'x' to 2 instead of 5 I get this:

>>>PositionLast(2, [2,5,2,3,5])
>>> 5

The answer here should be 2. I am confused as to how this is occurring, if anyone could explain to what I need to correct I would be grateful. I would also like to complete this with the most basic code possible.

Thank you.

Answer

Eugene Yarmash picture Eugene Yarmash · Dec 23, 2015

To do it efficiently, enumerate the list in reverse order and return the index of the first matching item (or None by default), e.g.:

def PositionLast(x, s):
    for i, v in enumerate(reversed(s)):
        if v == x:
            return len(s) - i - 1  # return the index in the original list
    return None

Avoid reversing the list using slice notation (e.g. s[::-1]) as that would create a new reversed list in memory, which is not necessary for the task.