Home > Blockchain >  How to see the negative index of an element in a list in python?
How to see the negative index of an element in a list in python?

Time:12-21

How can i see the negative index of an element in a list in python list.index() will inly return the positive index how do i get the negative index of it?

CodePudding user response:

A negative index is the index from the end of the list. You could calculate it by subtracting the length of the list from the positive index:

postive_index = some_list.index('some_value')
negative_index = positive_index - len(some_list)

CodePudding user response:

You can use a simple custom logic for this for example:

  1. get the index of the item
  2. subtract the length of the list from this value

Code

my_list = [x*2 for x in range(10)]
my_item = 12
print('list: ', my_list)
print('index: ', my_list.index(my_item))
neg_index = my_list.index(my_item) - len(my_list)
print('negative index: ', neg_index)
print('indexed item: ', my_list[neg_index])

Output

list:  [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
index:  6
negative index:  -4
indexed item:  12
  • Related