Rule Definition
Manipulating a list while iterating over it can end in unintended behavior. Iterators on the container are not going to be informed of the alteration and it is quite likely to produce a very different loop from that expected. The user must be careful because in the situation where "append()" is applied over the iterated list, the program might enter into an infinite loop.
Remediation
Decouple manipulation and iteration operations. This can be done with list comprehensions or by iterating over a copy of the list.
Violation Code Sample
mylist = [1, 2, 3, 4, 5]
for x in mylist:
mylist.remove(x)
The result after each iteration in the loop is:
[2, 3, 4, 5]
[2, 4, 5]
[2, 4]
Fixed Code Sample
#create a slice copy of mylist can be a first simple solution to avoid violation
mylist = [1, 2, 3, 4, 5]
for x in mylist[:]:
mylist.remove(x)
The result after each stage in for loop is:
[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]
Reference
https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating
https://docs.python.org/3.7/tutorial/controlflow.html#for-statements
Related Technologies
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.