Print duplicate elements index number in python

I have a string a = "ABCAB" and i want to print the index number of B.
My code:

a = "ABCAB"

for x in a:
    if x == 'B':
        print(a.index(x))

my output:

1
1

Expected output:

1
4

How can i fix this?

Hello there,

You will need to break out of the loop, once your condition is first met.

Hope this helps

1 Like

Try to use enumerate!

for index, letter in enumerate(a):
if letter == “B”:
print(index)

1 Like