Unused variable in for loop in Python
Prerequisite: Python For loops
The for loop has a loop variable that controls the iteration. Not all the loops utilize the loop variable inside the process carried out in the loop.
Using the loop variable inside : 2 4 6 8 10 Using the loop variable only for iteration : * * * * *
In the code snippet above, in loop-1, the loop control variable ‘i‘ is used inside the loop for computation. But in loop-2, the loop control variable ‘j‘ is concerned only with keeping tracking of the iteration number. Thus, ‘j’ is an unused variable in for loop. It is good practice to avoid declaring variables that are of no use. Some IDEs like Pycharm, PyDev, VSCode produce warning messages for such unused variables in the looping structure. The warning may look like something given below:
To avoid such warnings, the convention of naming the unused variable with an underscore(‘_’) alone can be used. This avoids the problem of unused variables in for loops. Consider the following script with an unused loop variable tested with the Vulture module in Python. Once the vulture module is installed using the pip command, it can be used for testing .py scripts in the anaconda prompt.
* * * * *
Checking with vulture module
To avoid this unused variable ‘i’ warning, the loop variable can simply be replaced by an underscore (‘_’). Look at the code snippet below
Some use pylint, a tool to keep track of code styles and dead code in Python. Such a tool can raise a warning when the variable in for loop is not used. To suppress that, it is better to use the underscore naming conventions for the unused variables.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course