1
a = ['AKDYYDSSGYHFDY', 'AKDDSSGYYFYFDY', 'AKDAGDYYYYGMDV']

match = ['DS', 'DV', 'DY']

counter = 0
for i in a:
    for j in match:
        if j in i:
            print(i, j)
            counter = counter+1
            continue

print(counter)

Results are

AKDYYDSSGYHFDY DS
AKDYYDSSGYHFDY DY
AKDDSSGYYFYFDY DS
AKDDSSGYYFYFDY DY
AKDAGDYYYYGMDV DV
AKDAGDYYYYGMDV DY

6

I was expecting that it would identify the first pattern DS in the first string in list a, then move to next element. However, it proceed to identify DY as well. What am I doing incorrectly? Any help is appreciated.

Thanks

fc27
  • 37
  • 3
  • 3
    I think you want `break` instead of `continue`? – Ryan Zhang Jul 07 '22 at 06:13
  • Does this answer your question? [Difference between break and continue statement](https://stackoverflow.com/questions/462373/difference-between-break-and-continue-statement) – SiHa Jul 07 '22 at 06:21

1 Answers1

1

Try to replace continue with break like this

a = ['AKDYYDSSGYHFDY', 'AKDDSSGYYFYFDY', 'AKDAGDYYYYGMDV']

match = ['DS', 'DV', 'DY']

counter = 0
for i in a:
    for j in match:
        if j in i:
            print(i, j)
            counter = counter+1
            break

print(counter)

Output:

AKDYYDSSGYHFDY DS
AKDDSSGYYFYFDY DS
AKDAGDYYYYGMDV DV
3

сontinue actually means that you go to the next iteration of for loop. Since you have continue inside j loop it doesn't influence on i loop and simply iterates more on j.

break instead stops iterations on j loop and let's i loop to proceed on the next iteration

olegr
  • 1,999
  • 18
  • 23