0

In my for loop, I got this code:

start = listData.index(datum) + 1

and listData is:

listData = ['H66', 'B35', 'L21', 'B35', 'H66', 'J02', 'J04', 'L21', 'J20']   

what I want is start = 1,2,3,4,5,6,7,9

but I got start = 1,2,3,2,1,6,7,3 (because index() return the index of the first occurrence? I guess?)

Is there any way to index last occurrence ?

dPdms
  • 173
  • 2
  • 14
  • 1
    with the last occurrence, you would have `5, 4, 8, 4, 5, 6, 7, 8, 9`... – njzk2 Apr 01 '16 at 04:04
  • I don't think that is what the OP wants exactly. He/She wants to find an occurrence of an element and then if needs to find again then it should prompt for the second occurrence. – JRodDynamite Apr 01 '16 at 04:13
  • If I'm correct, then the OP should rephrase the question for the post to be considered for reopening. – JRodDynamite Apr 01 '16 at 04:14

2 Answers2

3

How about:

start = len(listData) - listData[::-1].index(datum)

(ie. the last index is the first index from the reversed list)

Gerrat
  • 28,863
  • 9
  • 73
  • 101
1

Here you go:

>>> listData = ['H66', 'B35', 'L21', 'B35', 'H66', 'J02', 'J04', 'L21', 'J20']
>>> def return_last(x):
...     return len(listData)-listData[::-1].index(x)-1
... 
>>> return_last("L21")
7
>>> return_last("H66")
4
Hackaholic
  • 19,069
  • 5
  • 54
  • 72