Skip to content

For Index Replacement

Sourcery refactoring id: for-index-replacement

Description:

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

Before:

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

After:

for currency in currencies:
    print(currency)

Explanation:

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.