pythonic way to do something N times without an index variable?
A slightly faster approach than looping on xrange(N)
is:
import itertools
for _ in itertools.repeat(None, N):
do_something()
I just use for _ in range(n)
, it's straight to the point. It's going to generate the entire list for huge numbers in Python 2, but if you're using Python 3 it's not a problem.
Use the _
variable, like so:
# A long way to do integer exponentiation
num = 2
power = 3
product = 1
for _ in range(power):
product *= num
print(product)
since function is first-class citizen, you can write small wrapper (from Alex answers)
def repeat(f, N):
for _ in itertools.repeat(None, N): f()
then you can pass function as argument.