Is it possible to implement a Python for range loop without an iterator variable? Is it possible to implement a Python for range loop without an iterator variable? python python

Is it possible to implement a Python for range loop without an iterator variable?


Off the top of my head, no.

I think the best you could do is something like this:

def loop(f,n):    for i in xrange(n): f()loop(lambda: <insert expression here>, 5)

But I think you can just live with the extra i variable.

Here is the option to use the _ variable, which in reality, is just another variable.

for _ in range(n):    do_something()

Note that _ is assigned the last result that returned in an interactive python session:

>>> 1+23>>> _3

For this reason, I would not use it in this manner. I am unaware of any idiom as mentioned by Ryan. It can mess up your interpreter.

>>> for _ in xrange(10): pass...>>> _9>>> 1+23>>> _9

And according to Python grammar, it is an acceptable variable name:

identifier ::= (letter|"_") (letter | digit | "_")*


You may be looking for

for _ in itertools.repeat(None, times): ...

this is THE fastest way to iterate times times in Python.


The general idiom for assigning to a value that isn't used is to name it _.

for _ in range(times):    do_stuff()