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”Description:
Section titled “Description:”Replaces manual loop counter with call to enumerate
Before:
Section titled “Before:”i = 0for currency in currencies: print(i, currency) i += 1After:
Section titled “After:”for i, currency in enumerate(currencies): print(i, currency)Explanation:
Section titled “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.