This rule raises an issue when a loop iterates over enumerate() but accesses list elements by index instead of unpacking the value directly from the enumeration.

Why is this an issue?

The enumerate() function in Python is designed to provide both the index and the value of each element when iterating over a sequence. It returns tuples in the form (index, value) for each iteration.

When you use enumerate() in a loop but only unpack the index, then use that index to access the list element via subscript notation (e.g., lst[i]), you are performing an unnecessary lookup operation. The value you are looking up is already available from enumerate() itself - you are simply not capturing it.

This pattern does not take advantage of a built-in feature of enumerate() and results in:

The Pythonic approach is to unpack both values from the tuple that enumerate() returns. This makes the code clearer, more efficient, and more idiomatic.

What is the potential impact?

Non-idiomatic code patterns increase the cognitive load for developers maintaining the codebase. Over time, redundant index lookups can also mask bugs when the sequence is modified between the enumerate() call and the subscript access.

How to fix it

Unpack both the index and value from the enumerate() tuple directly in the loop declaration. Replace the subscript access with the unpacked value variable.

Code examples

Noncompliant code example

fruits = ['apple', 'banana', 'cherry']

for i, fruit in enumerate(fruits):
    print(f"Index {i}: {fruits[i]}")  # Noncompliant: use the unpacked value instead of "fruits[i]"

Compliant solution

fruits = ['apple', 'banana', 'cherry']

for i, fruit in enumerate(fruits):
    print(f"Index {i}: {fruit}")

Resources

Documentation