-1

Im trying to find the indexed version for multiple items in a list, such as

testarray = ["l","hello","l","l"]

for x in testarray:
    if x == "l":
        print(testarray.index(x))

I want the desired output to be 1, 3, 4, but what I'm getting is 1,1,1

AEM
  • 1,354
  • 8
  • 20
  • 30
  • 2
    Does this answer your question? [How to find all occurrences of an element in a list?](https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – mkrieger1 May 06 '20 at 22:41

1 Answers1

0

That's because list.index returns the index of the first occurrence of the element, to fix this, you can loop through the indices and values using enumerate:

testarray = ["l", "hello", "l", "l"]

for i, x in enumerate(testarray, 1):
    if x == "l":
        print(i)

Output:

1
3
4

In for i, x in enumerate(testarray, 1), i in the index, x is the value, and the second parameter 1 in enumerate tells it to start counting at 1 instead of by default at 0.

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55