Home > Software design >  What would the "Opposite" of an Index be?
What would the "Opposite" of an Index be?

Time:02-08

So I am currently writing a program where I have the position of an item in a list and I need to identify the element in that position.

How would I do that?

CodePudding user response:

list[position]

If you want to get multiple elements you can use ":"

list[position:position 1] returns a list with the list elements from position to but not including position 1.

CodePudding user response:

I think this example show how you can go from value to index and vice versa. Below list is a list of 100 random alphabet characters, then ind is a list of indexes where the character equals "A"

>>> import random
>>> import string
>>> list=random.choices(string.ascii_uppercase,k=100)
>>> ind=[]
>>> for i in range(len(list)):
...     if("A"==list[i]):
...             ind.append(i)
...
>>> ind
[31, 57, 90]
>>> for i in ind:
...     list[i]
...
'A'
'A'
'A'
  •  Tags:  
  • Related