Skip to content

For Index Replacement

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: for-index-replacement

Section titled “Sourcery refactoring id: for-index-replacement”

Replace item lookups in loops using the index with direct reference to the items

for i in range(len(currencies)):
print(currencies[i])
for currency in currencies:
print(currency)

A pattern that is often used in Python for loops is to use range(len(list)) to generate a range of numbers that can be iterated over.

If the index i is only used to do list access this code can be improved by iterating over the list directly, as in the above example.

This code is easier to understand, and a lot less cluttered. In particular being able to use a meaningful name for currency greatly improves readability.

Note that this refactoring will only trigger where Sourcery can determine that the collection (currencies in this case) is a list.