Search code examples
coding-stylefor-looppython

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


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?


Solution

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

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