pythonic way to do something N times without an index variable? [duplicate] Ask Question

pythonic way to do something N times without an index variable? [duplicate] Ask Question

I have some code like:

for i in range(N):
    do_something()

I want to do something N times. The code inside the loop doesn't depend on the value of i.

Is it possible to do this simple task without creating a useless index variable, or in an otherwise more elegant way? How?

ベストアンサー1

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

import itertools

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

おすすめ記事