2

So I'm checking a list and printing all the values that are equal to three

for item in top:
    if item == 3:
        print('recommendation found at:')
        print(top.index(item))

the problem is this will just continually print the first element that has the value 3. How can you print every the position of every element with the value 3?

Maxwell Omdal
  • 172
  • 3
  • 14

2 Answers2

2

Use enumerate.

>>> top = [1, 3, 7, 8, 3, -3, 3, 0]
>>> hits = (i for i,value in enumerate(top) if value == 3)

This is a generator that will yield all indices i where top[i] == 3.

>>> for i in hits:
...     print(i)
... 
1
4
6
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

From https://docs.python.org/2/tutorial/datastructures.html
Index: "Return the index in the list of the first item whose value is x."

a simple solution would be:

for i in range(len(top)):
    if top[i] == 3:
        print('recommendation found at: ' + str(i))
Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99