Iterate a certain number of times without storing the iteration number anywhere
Well I think the forloop you've provided in the question is about as good as it gets, but I want to point out that unused variables that have to be assigned can be assigned to the variable named _
, a convention for "discarding" the value assigned. Though the _
reference will hold the value you gave it, code linters and other developers will understand you aren't using that reference. So here's an example:
for _ in range(2):
print('Hello')
The idiom (shared by quite a few other languages) for an unused variable is a single underscore _
. Code analysers typically won't complain about _
being unused, and programmers will instantly know it's a shortcut for i_dont_care_wtf_you_put_here
. There is no way to iterate without having an item variable - as the Zen of Python puts it, "special cases aren't special enough to break the rules".
Others have addressed the inability to completely avoid an iteration variable in a for
loop, but there are options to reduce the work a tiny amount. range
has to generate a whole bunch of numbers after all, which involves a tiny amount of work; if you want to avoid even that, you can use itertools.repeat
to just get the same (ignored) value back over and over, which involves no creation/retrieval of different objects:
from itertools import repeat
for _ in repeat(None, 200): # Runs the loop 200 times
...
This will run faster in microbenchmarks than for _ in range(200):
, but if the loop body does meaningful work, it's a drop in the bucket. And unlike multiplying some anonymous sequence for your loop iterable, repeat
has only a trivial setup cost, with no memory overhead dependent on length.
exec 'print "hello";' * 2
should work, but I'm kind of ashamed that I thought of it.
Update: Just thought of another one:
for _ in " "*10: print "hello"