CodeQL documentation

Suspicious unused loop iteration variable

ID: py/unused-loop-variable
Kind: problem
Severity: error
Precision: high
   - maintainability
   - correctness
Query suites:
   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

A for loop iteration variable is not used in the body of the loop, and the loop does not count the number of items in the sequence. This is suspicious as there is rarely any reason to iterate over a sequence and not use the contents. Not using the loop variable can often indicate a logical error or typo.


Carefully check that the loop variable should not be used. If the variable is genuinely not being used and the code is correct, then rename the variable to _ or unused to indicate to readers of the code that it is intentionally unused.


In this example, the for loop iteration variable x is never used. It appears that the original test function was used to test TypeA and was subsequently modified to test TypeB as well.

def test():
    for t in [TypeA, TypeB]:
        x = TypeA()

It is likely that the change from x = TypeA() to x = t() was forgotten. The fixed version is shown below.

def test():
    for t in [TypeA, TypeB]:
        x = t