For loop of a list doesn't loop every element?

this is the code

await sleep(0)
for n in self.clones:
  n.sprite.kill()
  self.clones.remove(n)
  print(len(self.clones))
input("end")

and this is the output

link: https://replit.com/@s3D27ZHOU/project#project/project.py
the selected code is in line 423

ignore the n.sprite.kill because it basically kill something

supposedly it should loop every item in the list self.clones, delete it and kill it’s sprite.
However somehow it just sometime breaks itself out after looping half of the list

I don’t have any break keyword or anything that allows the program to exit itself, what happened???

You are modifying the list self.clones while iterating over it, when you remove elements from a list while iterating throught it can cause issues, cause the loop’s internal counter may get out of sync.

If you iterate over a shallow copy of the list (self.clones[:]), you can safely modify the original list (self.clones) without disrupting the loop

await sleep(0)
for n in self.clones[:]:  # Shallow copy
    n.sprite.kill()
    self.clones.remove(n)
    print(len(self.clones))
input("end")
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.