my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list)): # Noncompliant
print(i, my_list[i])
result = [data[i] * 2 for i in range(len(data))] # Noncompliant
Avoid the range(len()) pattern. Prefer direct iteration or enumerate() which avoids costly index-based access.
Using for i in range(len(sequence)) often leads to index-based access (sequence[i]), adding a getitem call and bounds checking on each iteration.
In many cases, iterating directly (or using enumerate() when you need the index) is faster for built-in sequences, though results can vary by data type and size.
Index-based access (sequence[i]) adds a getitem call + bounds checking per iteration
Direct iteration uses the iterator protocol (iter/next), optimized for built-in sequences
The pattern encourages developers to use index access when it is not needed
my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list)): # Noncompliant
print(i, my_list[i])
result = [data[i] * 2 for i in range(len(data))] # Noncompliant
my_list = [1, 2, 3, 4, 5]
# When you need the index AND the value
for i, item in enumerate(my_list): # Compliant
print(i, item)
# When you only need the value (often fastest and simplest)
for item in my_list: # Compliant
print(item)
# List comprehension
result = [val * 2 for val in data] # Compliant
The following results were obtained through local experiments.
CO2 Emissions Measurement: Using CodeCarbon