Skip to content

Replace For Index with Underscore

Sourcery refactoring id: for-index-underscore

Description:

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

Before:

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

After:

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

Explanation:

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.