Skip to content

Replace For Index with Underscore

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-underscore

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

Replaces an unused index in a for loop or comprehension with an underscore

for hat in my_wardrobe.hats:
shout("Hurrah!")
shouts = [shout("Hurrah!") for hat in my_wardrobe.hats]
for _ in my_wardrobe.hats:
shout("Hurrah!")
shouts = [shout("Hurrah!") for _ in my_wardrobe.hats]

Sometimes in a for loop or comprehension we just want some code to run a certain number of times, and don’t actually make use of the index variable.

In the above example we have introduced a new variable, hat, which we have to note when reading the code, but actually we don’t need it and could replace it with _:

It is a convention in Python to use _ as a throwaway name for unused variables. This means your brain can learn to safely ignore these, reducing the overhead to understand the code. Where you see this in a for loop or comprehension it is immediately clear that the loop is just used to repeat a block of code and we don’t care about the value being iterated over.