Possible Duplicate:
Finding first and last index of some value in a list in Python
Hi I was wondering if someone could help me with Python. I am trying to create a code that returns the last index of the last occurrence of an item in a list in a recursive way. So in a list [1,2,3,4,5,2] the last it should return 4. It only takes in 2 variables which are the list and the item that it is searching for. If it does not find any matching variable then it returns -1.
So far I have this:
def lstIndex(lst, item):
if len(lst) == 0:
return -1
place = lst[0]
if place == item:
print(place)
#just return the index
return lst.index(place)
else:
return lstIndex(lst[1:],item)
I’m not quite 100% sure I know what you want. Your statement that “… in a list of [1,2,3,4,5,2] the last it should return 4 …” has me a bit confused; I think you want to return the index of the last appearance of your specified
item. So, for 4 to be the result in the list specified,itemmust be 5.As noted elsewhere, a recursive function would not be the most efficient or Pythonic solution here. I’d prefer a solution like the first one in nneonneo’s answer.
However, if it must be recursive, I believe the code below gets what you want. Instead of stepping through the list from the front (by using
[1:]), you need to step backwards by using[:-1]as the index range when passing the list in the recursive call:I tested with the following:
With the following output: