James McMahon James McMahon - 1 year ago 65
Python Question

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

Is is possible to do this;

for i in range(some_number):
#do something

without the i? If you just want to do something x amount of times and don't need the iterator.

Answer Source

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):

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

>>> 1+2
>>> _

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
>>> _
>>> 1+2
>>> _

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download