Home > Blockchain >  How to print the highest index of an identical element in Python? [duplicate]
How to print the highest index of an identical element in Python? [duplicate]

Time:10-06

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!

CodePudding user response:

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)

CodePudding user response:

You can create a list containing the index of a specific number from a specific table:

def find_index(number,some_list):

   return([n for n, char in enumerate(some_list) if char==number])

So if your list is a = [0, 1, 1, 1, 1, 2, 1, 2] and you want to find the highest index location of 1 or 2:

print(find_index(1,a)[-1])

print(find_index(2,a)[-1])

  • Related