Use zip() to Iterate Parallel Lists
ID |
python.use_zip_iterate_lists |
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(a)): loops whose body subscripts at least two distinct collections by the same index. The idiom is the C-style index loop dressed in Python syntax; zip(a, b) produces the parallel iteration directly.
for i in range(len(items)): # FLAW
do(items[i], values[i])
for item, value in zip(items, values): # OK
do(item, value)
Rationale
The zip form makes the parallel-iteration intent explicit, removes the redundant len call, and avoids the off-by-one and length-mismatch bugs that lurk in index-based loops. When the lists may have different lengths, zip truncates to the shortest — usually the desired behaviour; itertools.zip_longest is available when explicit padding is needed.
Remediation
for item, value in zip(items, values):
process(item, value)
for i, (item, value) in enumerate(zip(items, values)):
process(i, item, value)