0

In a list of integer values

a = [4, 8, 2, 3, 8, 5, 8, 8, 1, 4, 8, 2, 1, 3]

I have to find the index of the last item with value 8. Is there more elegant way to do that rather than mine:

a = [4, 8, 2, 3, 8, 5, 8, 8, 1, 4, 8, 2, 1, 3]

for i in range(len(a)-1, -1, -1):
    if a[i] == 8:
        print(i)
        break
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
Igor234
  • 359
  • 1
  • 3
  • 11

3 Answers3

4

Try This:

a = [4, 8, 2, 3, 8, 5, 8, 8, 1, 4, 8, 2, 1, 3]
index = len(a) - 1 - a[::-1].index(8)

Just reverse the array and find first index of element and then subtract it from length of array.

Rohit-Pandey
  • 2,039
  • 17
  • 24
1
>>> lst = [4, 8, 2, 3, 8, 5, 8, 8, 1, 4, 8, 2, 1, 3]
>>> next(i for i in range(len(lst)-1, -1, -1) if lst[i] == 8)
10

This throws StopIteration if the list doesn't contain the search value.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
0

Use sorted on all indexes of items with a value of 8 and take the last value, or using reverse = True take the first value

x = sorted(i for i, v in enumerate(a) if v == 8)[-1]

print(x) # => 10
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20