Skip to content

Convert to Enumerate

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: convert-to-enumerate

Section titled “Sourcery refactoring id: convert-to-enumerate”

Replaces manual loop counter with call to enumerate

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

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.