Search code examples
pythoncoding-stylepylintdummy-data

how do you make a For loop when you don't need index in python?


If I need a for loop in Python:

for i in range(1,42):
    print "spam"

but don't use the i for anything, pylint complains about the unused variable. How should I handle this? I know you can do this:

for dummy_index in range(1,42):
    print "spam"

but doing this seems quite strange to me. Is there a better way?

I'm quite new to Python, so forgive me if I'm missing something obvious.


Solution

  • There is no "natural" way to loop n times without a counter variable in Python, and you should not resort to ugly hacks just to silence code analyzers.

    In your case I would suggest one of the following:

    • Just ignore the PyLint warning (or filter reported warnings for one-character variables)
    • Configure PyLint to ignore variables named i, that are usually only used in for loops anyway.
    • Mark unused variables using a prefix, probably using the default _ (it's less distracting than dummy)