Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | Last occurrence of some element in a list

Python | Last occurrence of some element in a list

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




# Python3 code to demonstrate
# to get last element occurrence
# using join() + rfind()
 
# initializing list
test_list = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r',
             'g', 'e', 'e', 'k', 's']
 
# using join() + rfind()
# to get last element occurrence
res = ''.join(test_list).rindex('e')
 
# printing result
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




# Python3 code to demonstrate
# to get last element occurrence
# using List Slice + index()
 
# initializing list
test_list = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r',
             'g', 'e', 'e', 'k', 's']
 
# using List Slice + index()
# to get last element occurrence
res = len(test_list) - 1 - test_list[::-1].index('e')
 
# printing result
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




# Python3 code to demonstrate
# to get last element occurrence
# using max() + enumerate()
 
# initializing list
test_list = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r',
             'g', 'e', 'e', 'k', 's']
 
# using max() + enumerate()
# to get last element occurrence
res = max(idx for idx, val in enumerate(test_list)
          if val == 'e')
 
# printing result
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




# Python3 code to demonstrate
# to get last element occurrence
 
# initializing list
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")
# printing result
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 the function
test_list = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r',
             'g', 'e', 'e', 'k', 's']
print(last_occurrence(test_list, 'e'))  # should print 10
#This code is contributed by Edula Vinay Kumar Reddy


Output

10

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)

RELATED ARTICLES

Most Popular

Recent Comments