Home > Software engineering >  Why does this for each loop repeat infinitely when an if else is inside?
Why does this for each loop repeat infinitely when an if else is inside?

Time:10-21

I'm observing some very strange behavior of a for each loop. When the if/else blocks are present, an infinite loop results. However, when they are commented out, and only the print(motif) remains in the loop, the expected behavior results, looping through the list 4 times. I should mention the the motif_seqs list was assigned to this new list at this point in the code, which may somehow influence the behavior.

motif_seqs = ["polyA", "polyT", "polyG", "polyC"]

for motif in motif_seqs:
    if motif == "homopolymer":
        pass
    else:
        motif_seqs.append(motif) 
    print(motif)

CodePudding user response:

You are adding items to the list in your else statement. Since your condition always fails, it moves to the else branch which adds items to the list and makes it so that the list never ends.

CodePudding user response:

Since your condition if motif == "homopolymer": always fails, it goes to else block. And in else block you are appending the iterable to the iterating list itself. The list grows continously and your loop goes for infinity.

  • Related