Open In App

Unused variable in for loop in Python

Last Updated : 01 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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.  

Example:

Python3




# i,j - loop variable
  
# loop-1
print("Using the loop variable inside :")
  
# used loop variable
for i in range(0, 5):
  
    x = (i+1)*2
    print(x, end=" ")
  
# loop-2
print("\nUsing the loop variable only for iteration :")
  
# unsused loop variable
for j in range(0, 5):
  
    print('*', end=" ")


Output

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:

unused variable warning in vscode

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. 

Example: trial1.py

Python3




# unused function
def my_func():
  
    # unused local variable
    a = 5
    b = 2
    c = b+2
    print(b, c)
  
  
# unused loop variable 'i'
for i in range(0, 5):
    print("*", end=" ")


Output

* * * * * 

Checking with vulture module

vulture module-dead code check

To avoid this unused variable ‘i’ warning, the loop variable can simply be replaced by an underscore (‘_’). Look at the code snippet below

Python3




# unused function
def my_func():
    b = 2
    c = b+2
    print(b, c)
  
  
# unused loop variable 'i'
for _ in range(0, 5):
    print("*", end=" ")



vulture module-dead code check

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads