python.lang.correctness.list-modify-iterating.list-modify-while-iterate

Verifed by r2c
Community Favorite
profile photo of semgrepsemgrep
Author
89,146
Download Count*

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(...)
      - pattern: |
          for $ELEMENT in $LIST:
            ...
            $LIST.remove(...)
    metadata:
      category: correctness
      technology:
        - python
      references:
        - https://unspecified.wordpress.com/2009/02/12/thou-shalt-not-modify-a-list-during-iteration/
      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)

# ruleid:list-modify-while-iterate
for i in e:
    if i == 1:
        e.remove(i)