python.lang.correctness.list-modify-iterating.list-modify-while-iterate
Verifed by r2c
Community Favorite

Author
89,146
Download Count*
License
It appears that $LIST
is a list that is being modified while in a for loop. This will likely cause a runtime error or an infinite loop.
Run Locally
Run in CI
Defintion
rules:
- id: list-modify-while-iterate
message: It appears that `$LIST` is a list that is being modified while in a for
loop. This will likely cause a runtime error or an infinite loop.
languages:
- python
severity: ERROR
pattern-either:
- pattern: |
for $ELEMENT in $LIST:
...
$LIST.pop(...)
- pattern: |
for $ELEMENT in $LIST:
...
$LIST.push(...)
- pattern: |
for $ELEMENT in $LIST:
...
$LIST.append(...)
- pattern: |
for $ELEMENT in $LIST:
...
$LIST.extend(...)
metadata:
category: correctness
technology:
- python
license: Commons Clause License Condition v1.0[LGPL-2.1-only]
Examples
list-modify-iterating.py
l = list(range(100))
# ruleid:list-modify-while-iterate
for i in l:
print(i),
print(l.pop(0))
x = l.pop(0)
print(x)
a = [1, 2, 3, 4]
# ruleid:list-modify-while-iterate
for i in a:
print(i)
a.pop(0)
b = [1, 2, 3, 4]
# ruleid:list-modify-while-iterate
for i in b:
print(i)
b.append(0)
c = []
# ok:list-modify-while-iterate
for i in range(5):
print(i)
c.append(i)
d = []
e = [1, 2, 3, 4]
# ok:list-modify-while-iterate
for i in e:
print(i)
d.append(i)
Short Link: https://sg.run/0Qr5