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
3

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.