Skip to content

Convert to Enumerate

Sourcery refactoring id: convert-to-enumerate

Description:

Replaces manual loop counter with call to enumerate

Before:

i = 0
for currency in currencies:
    print(i, currency)
    i += 1

After:

for i, currency in enumerate(currencies):
    print(i, currency)

Explanation:

When iterating over a list you sometimes need access to a loop counter that will let you know the index of the element you are utilising.

Using the built-in Python function, enumerate, lets you generate an index directly, removing two unneeded lines of code.

When reading this we don't have to worry about the book-keeping of the i variable, letting us focus in on the code that really matters.