No for i in range(len(x))
ID |
python.no_range_loop_with_len |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
Python |
Tags |
best-practice, code-style |
Description
Reports for i in range(len(x)): loops. The idiom is the C-style index loop ported to Python; enumerate(x) reads better, gives both the index and the value, and avoids the redundant len call. When only the value is needed, for item in x: is the right form.
for i in range(len(items)): # FLAW
do(items[i])
for i, item in enumerate(items): # OK
do(item)
for item in items: # OK
do(item)
Rationale
The range(len(…)) form keeps a Python beginner thinking in indices, which loses the speed and readability benefits of native iteration and risks off-by-one bugs. enumerate is also more amenable to sharing the loop body with other iteration patterns (e.g., zip(items, indices)).
Remediation
for i, item in enumerate(items):
process(i, item)
# or, when the index is not actually used:
for item in items:
process(item)