Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding the last occurrence of an item in a list python

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.

like image 977
efc1 Avatar asked Dec 23 '15 15:12

efc1


People also ask

How do you find the last element in a list index?

Get the last element of the list using the “length of list - 1” as an index and print the resultant last element of the list. Get the last element of the list using − 1(negative indexing) as the index and print the resultant last element of the list.

How do you print the last element in a list Python?

a=["first","second from last","last"] # A sample list print(a[0]) #prints the first item in the list because the index of the list always starts from 0. print(a[-1]) #prints the last item in the list.


2 Answers

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.

like image 159
Eugene Yarmash Avatar answered Oct 13 '22 00:10

Eugene Yarmash


Your logic is incorrect, because you return the count if i==x and you have an extra loop at the trailing of your function.

Instead you loop over the reverse forms of enumerate of your list and return the index of first occurrence :

def PositionLast (x,s):
    return next(i for i,j in list(enumerate(s))[::-1] if j == x)

Demo:

print PositionLast (2, [2,5,2,3,5,3])
2
print PositionLast (3, [2,5,2,3,5,3])
5
print PositionLast (5, [2,5,2,3,5,3])
4
like image 26
Mazdak Avatar answered Oct 13 '22 01:10

Mazdak