+ 1

What is going wrong ??

def lastOccr(list,n): last = list[0] for i in list: if i == n: last = i return list.index(last) list = [0,1,5,9,5,6,5,0,4,1] print(lastOccr(list,5))

8th Apr 2022, 9:33 AM
ELL
ELL - avatar
8 Answers
+ 4
You can use enumerate() to get any position of the same element in a list. def lastOccr(list,n): last = list[0] for i,e in enumerate(list): if e == n: last = i return last list = [0,1,5,9,5,6,5,0,4,1] print(lastOccr(list,5))
8th Apr 2022, 10:05 AM
Simba
Simba - avatar
+ 3
Adi 5 == 5 so last = 5 And list.index(5) = 2 #this is the index of first 5 not last 5
8th Apr 2022, 9:37 AM
A͢J
A͢J - avatar
+ 3
Adi You can get all indexes and last index using this logic. #What is going wrong ?? def lastOccr(list, n): return [i for i, x in enumerate(list) if x == n] list = [0,1,5,9,5,6,5,0,4,1] indexes = lastOccr(list, 5) print (indexes) #all indexes print (indexes[-1]) #last index
8th Apr 2022, 11:47 AM
A͢J
A͢J - avatar
+ 2
3 versions as the comments show: # version using list iteration def lastOccr1(lst_, number): for ndx, num in enumerate(lst_): if num == number: ndx_pos = ndx return ndx_pos # version using string with rindex() method, thst starts searching from the right side of string def lastOccr2(lst_, number): return ''.join(map(str, lst_)).rindex(str(number)) # using enumerate to create the index values, then use max() function def lastOccr3(lst_, number): return max([ndx for ndx, num in enumerate(lst_) if num == number]) lst = [0,1,5,9,5,6,5,0,4,1] print(lastOccr1(lst, 5)) print(lastOccr2(lst, 5)) print(lastOccr3(lst, 5))
8th Apr 2022, 8:17 PM
Lothar
Lothar - avatar
+ 1
What is your expected output.. list.index() returns first occurence index
8th Apr 2022, 9:37 AM
Jayakrishna 🇮🇳
+ 1
So how can i get the last occr index?
8th Apr 2022, 9:42 AM
ELL
ELL - avatar
+ 1
Try to pass your list but reversed. lastOccr(list[::-1], 5) In a reverse list, the index of the first occurrence of n will be the index of the last in your standard list. However, this method requires an extra step in which you must calculate the real index with the reversed index and your original list's length.
8th Apr 2022, 9:50 AM
Orisa
Orisa - avatar
+ 1
#your way modified def lastOccr(list,n): last = -1 for i in range(len(list)): if list[i] == n: last = i return last list = [0,1,5,9,5,6,5,0,4,1] print(lastOccr(list,5)) #Or print(len(list) - list[::-1].index(5) -1) #this works fine if element is in list, else throws error... hope it helps..
8th Apr 2022, 11:53 AM
Jayakrishna 🇮🇳