This rule raises an issue when a nested loop uses the same variable name as an outer loop, causing the inner loop to shadow the outer loop variable.
In Python, loop variables persist after the loop completes and can be reassigned by inner loops without any warning. Unlike languages with block-scoped variables, Python allows inner loops to silently overwrite outer loop variables, making the outer variable inaccessible within the inner loop scope.
This pattern almost always indicates a programmer error. Common scenarios include copying loop patterns without changing variable names, or confusion about Python's scoping rules. The shadowing happens silently without any compiler or runtime warning, making these bugs difficult to spot.
Use different variable names for each loop. Choose descriptive names that reflect what each variable represents.
for i in range(10):
print(f"Outer: {i}")
for i in range(5): # Noncompliant
print(f"Inner: {i}")
# i now contains 4, not the outer loop value
for i in range(10):
print(f"Outer: {i}")
for j in range(5):
print(f"Inner: {j}")
# i still contains the outer loop value