There are many ways to find out the first index of element in the list as Python in its language provides index() function that returns the index of first occurrence of element in list. But if one desires to get the last occurrence of element in list, usually a longer method has to be applied. Let’s discuss certain shorthands to achieve this particular task.
Method #1 : Using join() + rfind() This is usually the hack that we can employ to achieve this task. Joining the entire list and then employing string function rfind() to get the first element from right i.e last index of element in list.
Python3
test_list = [ 'G' , 'e' , 'e' , 'k' , 's' , 'f' , 'o' , 'r' ,
'g' , 'e' , 'e' , 'k' , 's' ]
res = ' '.join(test_list).rindex(' e')
print ( "The index of last element occurrence: " + str (res))
|
Output:
The index of last element occurrence: 10
Time Complexity: O(n), where n is the length of the input list. This is because we’re using join() + rfind() which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2: Using List Slice + index() Using list slicing we reverse the list and use the conventional index method to get the index of first occurrence of element. Due to the reversed list, the last occurrence is returned rather than the first index of list.
Python3
test_list = [ 'G' , 'e' , 'e' , 'k' , 's' , 'f' , 'o' , 'r' ,
'g' , 'e' , 'e' , 'k' , 's' ]
res = len (test_list) - 1 - test_list[:: - 1 ].index( 'e' )
print ( "The index of last element occurrence: " + str (res))
|
Output:
The index of last element occurrence: 10
Method #3 : Using max() + enumerate() We use enumerate function to get the list of all the elements having the particular element and then max() is employed to get max i.e last index of the list.
Python3
test_list = [ 'G' , 'e' , 'e' , 'k' , 's' , 'f' , 'o' , 'r' ,
'g' , 'e' , 'e' , 'k' , 's' ]
res = max (idx for idx, val in enumerate (test_list)
if val = = 'e' )
print ( "The index of last element occurrence: " + str (res))
|
Output:
The index of last element occurrence: 10
Time complexity: O(n)
Auxiliary space: O(n), where n is length of list
Method #4 : Using replace() and index() methods
Python3
test_list = [ 'G' , 'e' , 'e' , 'k' , 's' , 'f' , 'o' , 'r' ,
'g' , 'e' , 'e' , 'k' , 's' ]
x = "".join(test_list)
a = x.count( "e" )
i = 1
while (i<a):
x = x.replace( "e" , "*" , 1 )
i + = 1
res = x.index( "e" )
print ( "The index of last element occurrence: " + str (res))
|
Output
The index of last element occurrence: 10
Time complexity: O(n)
Auxiliary space: O(n), where n is length of list
Method #5 : Using try/except and index():
Here is another approach to finding the last occurrence of an element in a list, using try/except and index():
Python3
def last_occurrence(lst, val):
index = - 1
while True :
try :
index = lst.index(val, index + 1 )
except ValueError:
return index
test_list = [ 'G' , 'e' , 'e' , 'k' , 's' , 'f' , 'o' , 'r' ,
'g' , 'e' , 'e' , 'k' , 's' ]
print (last_occurrence(test_list, 'e' ))
|
This approach uses a loop to repeatedly call the index() method on the list, starting from the index after the previous occurrence of val and going to the end of the list. When val is not found, the index() method raises a ValueError, which is caught by the try block and causes the function to return the last index at which val was found. If val is not found in the list, the function returns -1.
Time complexity: O(n)
Auxiliary space: O(1)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
17 Apr, 2023
Like Article
Save Article