Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Last occurrence of some element in a list in Python
Finding the last occurrence of an element in a list is a common task in Python. There are several efficient approaches to accomplish this, each with different advantages depending on your specific needs.
Using Reverse and Index Method
The first approach reverses the list and finds the first occurrence, then calculates the original position ?
# 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
final_index = len(words) - index - 1
print(f"Last occurrence of '{element}' is at index: {final_index}")
Last occurrence of 'sleep' is at index: 5
Using Enumerate with Max
This method finds all occurrences and returns the maximum index ?
# initializing the list
words = ['eat', 'sleep', 'drink', 'sleep', 'drink', 'sleep', 'go', 'come']
element = 'sleep'
# finding the last occurrence using enumerate
final_index = max(index for index, item in enumerate(words) if item == element)
# printing the index
print(f"Last occurrence of '{element}' is at index: {final_index}")
Last occurrence of 'sleep' is at index: 5
Using Reverse Range Loop
Loop backwards through the list to find the first match from the end ?
# initializing the list
words = ['eat', 'sleep', 'drink', 'sleep', 'drink', 'sleep', 'go', 'come']
element = 'sleep'
# finding last occurrence by looping backwards
final_index = -1
for i in range(len(words) - 1, -1, -1):
if words[i] == element:
final_index = i
break
print(f"Last occurrence of '{element}' is at index: {final_index}")
Last occurrence of 'sleep' is at index: 5
Comparison of Methods
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Reverse + Index | O(n) | O(1) | Simple implementation |
| Enumerate + Max | O(n) | O(n) | Functional programming style |
| Reverse Range | O(n) worst case | O(1) | Early exit optimization |
Conclusion
Use the reverse range method for better performance when the element appears frequently near the end. The enumerate approach is more readable but uses extra memory for large lists.
Advertisements
