pythonic way to do something N times without an index variable? pythonic way to do something N times without an index variable? python python

pythonic way to do something N times without an index variable?


A slightly faster approach than looping on xrange(N) is:

import itertoolsfor _ in itertools.repeat(None, N):    do_something()


Use the _ variable, as I learned when I asked this question, for example:

# A long way to do integer exponentiationnum = 2power = 3product = 1for _ in xrange(power):    product *= numprint product


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.


matomo