0

I am having an issue to find the index of each similar values within a list.

Example:

b = ["a", "b", "a", "a", "b", "b"]
for x in b:
    if "a" in x:
        print(b.index(x))

my current results:

0
0
0

expected results:

0
2
3

(In my actual case we have two to 100 of similar values within a list so .index is not working well.)

Grismar
  • 20,449
  • 4
  • 26
  • 46
Anonymous
  • 477
  • 3
  • 11

4 Answers4

3

Use enumerate:

[n for n, i in enumerate(b) if i == 'a']

Output:

[0, 2, 3]
Chris
  • 27,139
  • 3
  • 23
  • 44
3

This is a problem of algorithm. the method of list.index(val) returns the index of the first value to appear. If you want to find all indices of similar values, then you need to change your algorithm.

A common brute force approach for this is like:

b = ["a", "b", "a", "a", "b", "b"]
for i in range(len(b)):
    if b[i] == 'a':
        print(i)

Which will probably output, as you have said:

0
2
3
Seraph Wedd
  • 814
  • 5
  • 14
1

Fairly straightforward:

def indices(arr, val):
    return [n for n, x in enumerate(arr) if x == val]

b = ["a", "b", "a", "a", "b", "b"]

print(indices(b, "a"))
Grismar
  • 20,449
  • 4
  • 26
  • 46
0

Correct Code:

characters = ["a", "b", "a", "a", "b", "b"]
for i in range(len(characters)):
    if characters[i] == "a":
        print(i)
Mike
  • 1,231
  • 10
  • 17