Last occurrence of some element in a list in Python


In this article, we are going to see different ways to find the last occurrence of an element in a list.

Let's see how to find the last occurrence of an element by reversing the given list. Follow the below steps to write the code.

  • Initialize the list.
  • Reverse the list using reverse method.
  • Find the index of the element using index method.
  • The actual index of the element is len(list) - index - 1.
  • Print the final index.

Example

Let's see the code.

 Live Demo

# initializing the list
words = ['eat', 'sleep', 'drink', 'sleep', 'drink', 'sleep', 'go', 'come']
element = 'sleep'

# reversing the list
words.reverse()

# finding the index of element
index = words.index(element)

# printing the final index
print(len(words) - index - 1)

If you run the above code, then you will get the following result.

Output

5

Another way is to find all the indexes and getting the max from it.

Example

Let's see the code.

 Live Demo

# initializing the list
words = ['eat', 'sleep', 'drink', 'sleep', 'drink', 'sleep', 'go', 'come']
element = 'sleep'

# finding the last occurrence
final_index = max(index for index, item in enumerate(words) if item == element)

# printing the index
print(final_index)

If you run the above code, then you will get the following result.

Output

5

Conclusion

If you have any queries in the article, mention them in the comment section.

Updated on: 13-Nov-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements