How to print the highest index of an identical element in Python?

Issue

Let’s say we have a list:

[0, 1, 1, 2, 3, 2, 2]

or

[0, 1, 1, 1, 1, 2, 1, 2]

or

[0, 2, 2, 1, 1, 2, 1]

How do we always print highest index with the identical number? So if we want to find highest index of "1" in the first list, it would return index 2, for second list index 6, third list index 6. How do we achieve this? Thank you!

Solution

you can check for the index from the end, and do some math on the list afterwards.

arr = [0, 1, 1, 2, 3, 2, 2]
number_to_index = 1
len(arr) - 1 - arr[::-1].index(number_to_index)

Answered By – Mahrkeenerh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published