1

I am trying to access specific elements in a list within a for loop. However, when a repeated item appears the index is given for the first instance.

For example:

my_list = [1,2,2,3,2,1]
for i in my_list:
     return my_list.index(i)

When the for loop has reached the last element it will return 0 rather than my desired output of 5. How do I get the index of the specific 'i' the loop is using?

Badgy
  • 774
  • 3
  • 14

2 Answers2

0

Let say you want to find:

index_of = 2

Now lets get index of that element:

 [i for i in range(len([1,2,2,3,2,1])) if [1,2,2,3,2,1][i] ==index_of]

gives all index of that element:

[1, 2, 4]
Joshua
  • 4,674
  • 1
  • 6
  • 30
0

Use enumerate():

for index, value in enumerate(my_list):
    print('Value {} at position {}'.format(value, index))
Olvin Roght
  • 5,080
  • 2
  • 11
  • 27
Cblopez
  • 396
  • 1
  • 12