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
  • 27,561
  • 4
  • 31
  • 54
Anonymous
  • 477
  • 3
  • 12
  • Not sure what you are trying to do. Are you only interested in finding the indices of `"a"`? – Selcuk Aug 27 '19 at 01:27
  • Yes, I wanted to learn new methods and just in case I came across such issue in the future. – Anonymous Aug 27 '19 at 01:27
  • You may want to look up the built-in [enumerate](https://docs.python.org/3/library/functions.html#enumerate) function. –  Aug 27 '19 at 01:32

4 Answers4

3

Use enumerate:

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

Output:

[0, 2, 3]
Chris
  • 29,127
  • 3
  • 28
  • 51
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
  • 864
  • 6
  • 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
  • 27,561
  • 4
  • 31
  • 54
0

Correct Code:

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