Skip to content

Replace index with underscore

Sourcery refactoring id: for-index-underscore


Replaces an unused index in a for loop with an underscore


for hat in my_wardrobe.hats:


for _ in my_wardrobe.hats:


Sometimes in a for loop 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 it it 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.

Back to top