w3resource

Python: Find the last occurrence of a specified item in a given list

Python List: Exercise - 162 with Solution

Write a Python program to find the last occurrence of a specified item in a given list.

Sample Solution:

Python Code:

def last_occurrence(l1, ch):
    return ''.join(l1).rindex(ch)

chars = ['s','d','f','s','d','f','s','f','k','o','p','i','w','e','k','c']
print("Original list:")
print(chars)
ch = 'f'
print("Last occurrence of",ch,"in the said list:")
print(last_occurrence(chars, ch))
ch = 'c'
print("Last occurrence of",ch,"in the said list:")
print(last_occurrence(chars, ch))
ch = 'k'
print("Last occurrence of",ch,"in the said list:")
print(last_occurrence(chars, ch))
ch = 'w'
print("Last occurrence of",ch,"in the said list:")
print(last_occurrence(chars, ch)) 

Sample Output:

Original list:
['s', 'd', 'f', 's', 'd', 'f', 's', 'f', 'k', 'o', 'p', 'i', 'w', 'e', 'k', 'c']
Last occurrence of f in the said list:
7
Last occurrence of c in the said list:
15
Last occurrence of k in the said list:
14
Last occurrence of w in the said list:
12

Pictorial Presentation:

Python List: Find the last occurrence of a specified item in a given list.

Flowchart:

Flowchart: Find the last occurrence of a specified item in a given list.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to check if a given list is strictly increasing or not. Moreover, If removing only one element from the list results in a strictly increasing list, we still consider the list true.
Next: Write a Python program to get the index of the first element which is greater than a specified element.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Returns True if the provided function returns True for every element in the list, False otherwise:

Example:

def tips_every(lst, fn=lambda x: x):
  return all(map(fn, lst))

print(tips_every([2, 4, 3], lambda x: x > 1))
print(tips_every([1, 2, 3]))

Output:

True
True