0

for example, there is a list:

numbers = [1,2,3,4,2,1]
print(numbers.index(1))

output is 0

element behind is preferred means that, the index of the "1" at the end should be printed instead of the the "1" at the beginning. i.e. output should be 5

A baseline method of "reverse the list" is provided bellow, it there a faster & simpler way to do this?

numbers = [1,2,3,4,2,1]
numbers.reverse()
output = []
for i in range(1,4):
    inv_inx= len(numbers)-numbers.index(i)-1
    output.append(inv_inx)
print(output)
assert output == [5, 4, 2]
zheyuanWang
  • 1,158
  • 2
  • 16
  • 30

3 Answers3

1

An approach that doesn't make any temporary lists, scans from the end (so it doesn't find all the 1s you don't care about) and short-circuits (so it stops when the element is found) is to combine a generator expression with the next, reversed and enumerate built-ins:

def rindex(seq, value):
    return len(seq) - next(i for i, x in enumerate(reversed(seq), 1) if x == value)

This will raise StopIteration if the value is not found, if you want it to raise ValueError, you just have to convert it:

def rindex(seq, value):
    try:
        return len(seq) - next(i for i, x in enumerate(reversed(seq), 1) if x == value)
    except StopIteration:
        raise ValueError(f"{value!r} is not in {type(seq).__name__}")  # Rough equivalent to list.index message

For comparison, a version without a generator expression or next would look like this:

def rindex(seq, value):
    for i, x in enumerate(reversed(seq), 1):
        if x == value:
            return len(seq) - i
    raise ValueError(f"{value!r} is not in {type(seq).__name__}")
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

You can start the search from the end of the list:

The list index() method can take a maximum of three arguments:

element - the element to be searched

start (optional) - start searching from this index

end (optional) - search the element up to this index

numbers = [1,2,3,4,2,1]
print(numbers.index(1,-1))

OUTPUT:

5

EDIT:

If the search item is not in the end of the list:

lst = [1,2,3,4,2,1,2]

print(len(lst)-1 - lst[::-1].index(1))   # 5

Source

DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

try this not the best solution but better.

numbers = [1,2,1,4,2,1]
count=0
for i in numbers :
    count=count+1
    if i == 1:
        a=[]
        a.append(count-1)
print(a)    #5