Finding the last occurrence of an item in a python list

I want to find the last occurrence of the element 'x' in the sequence 's' or return None if it is not there and the position of the first element is 0

This is what I 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 the following:

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

The answer here should be 2. I am confused about how this happens, if someone can explain what I need to fix, I would be grateful. I would also like to complete this with the most basic code.

Thanks.

+5
source share
7 answers

There is no rindex method in the pity lists, but you can use index :

 last = len(s) - s[::-1].index(x) - 1 

or equivalent

 for i, v in enumerate(reversed(s)): if v == x: last = len(s) - i - 1 break 
+5
source

Your logic is wrong because you are returning a counter if i==x , and you have an extra loop at the end of your function.

Instead, you iterate over the inverse listing forms of your list and return the index of the 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 
+3
source

Your code is incorrect, it checks the list from the very beginning and stops in the first match, and you want to check the list in reverse order.

 def PositionLast (x,s): count = len(s) for i in s[::-1]: count -= 1 if i == x: return count return None 

Your first line gives the correct answer just because of a match:
- Counts the value 5 when checking the first element.
- The score is 4 when checking the second element, it matches, then 4 is returned.
“Coincidentally, this is the index of your last subject.”

+2
source

Enumerate the list in reverse order, and then check x. This can be an effective way, since reversing the list and then searching for the index from the beginning is resource intensive.

 def PositionLast (x,s): for i in range(len(s)-1,0,-1): if s[i] == x: return i return None 
+2
source
 def positionLast(x, L): answer = None for i,e in enumerate(L): if e==x: answer = i return answer 
+1
source
 def positionLast(x, L): try: return max(i for i,e in enumerate(L) if e==x) except: return None 
0
source

Thanks to everyone for the answers and help! Unfortunately, no one had the answer I was looking for, but no matter what, I did it myself, but thank you all the same!

Here is the final code:

 def PositionLast(x,s): count = -1 position = None for i in s: count += 1 if i == x: position = count return position 

This returns the correct answers to all my tests.

Thanks, Aimer.

0
source

Source: https://habr.com/ru/post/1239069/


All Articles