Iterate a certain number of times without storing the iteration number anywhere
Solution 1
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"
Solution 2
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')
Solution 3
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.
Solution 4
Although I agree completely with delnan's answer, it's not impossible:
loop = range(NUM_ITERATIONS+1)
while loop.pop():
do_stuff()
Note, however, that this will not work for an arbitrary list: If the first value in the list (the last one popped) does not evaluate to False
, you will get another iteration and an exception on the next pass: IndexError: pop from empty list
. Also, your list (loop
) will be empty after the loop.
Just for curiosity's sake. ;)
Solution 5
Sorry, but in order to iterate over anything in any language, Python and English included, an index must be stored. Be it in a variable or not. Finding a way to obscure the fact that python is internally tracking the for loop won't change the fact that it is. I'd recommend just leaving it as is.
BorrajaX
Updated on July 08, 2022Comments
-
BorrajaX almost 2 years
I was wondering if it is possible to perform a certain number of operations without storing the loop iteration number anywhere.
For instance, let's say I want to print two
"hello"
messages to the console. Right now I know I can do:for i in range(2): print "hello"
but then the
i
variable is going to take the values0
and1
(which I don't really need). Is there a way to achieve the same thing without storing those unwanted values anywhere?Needless to say, using a variable is not a big deal at all... I'm just curious.