pythonfor-loop

Is it OK to not use the value of the index 'i' inside a for loop?


Would it be frowned upon if the index variable i were not used inside a for loop? I have never come across a code that didn't use the value of the index while it iterates through the loop.

def questionable():
    for i in range(3):
        print('Is this OK?') # (or do something more complicated)

# as opposed to:

def proper():
    for i in range(3):
        print(i) # (or do something that the value of 'i' is necessary)

What's a more Pythonic way to rewrite the function questionable, that is, to repeatedly do something without using the iteration variable?


Solution

  • When you want to perform an action a certain number of times without caring about the loop variable, the convention is to use an underscore (_) instead of a named variable like i. This signals to readers of your code: "I'm not going to use this variable."

    So your questionable function can be rewritten in a more Pythonic way like this:

    def more_pythonic():
        for _ in range(3):
            print('Is this OK?')