
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
# 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.
# 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.
- Related Articles
- How to find the last occurrence of an element in a Java List?
- Program to remove last occurrence of a given target from a linked list in Python
- How to get the last element of a list in Python?
- How to get the second-to-last element of a list in Python?
- Find the last element of a list in scala
- Python How to get the last element of list
- Python - First occurrence of one list in another
- How to find index of last occurrence of a substring in a string in Python?
- Count tuples occurrence in list of tuples in Python
- Count occurrence of all elements of list in a tuple in Python
- How to replace the last occurrence of an expression in a string in Python?
- Python – Nearest occurrence between two elements in a List
- Sort tuple based on occurrence of first element in Python
- Finding the last occurrence of a character in a String in Java
- Program to find duplicate elements and delete last occurrence of them in Python

Advertisements