Search code snippets, questions, articles...

Run a for loop N times in python

This code snippet will show you how to run a for loop N times in python. For example, let's say you want to loop 4 times then below is the code.
import itertools

N = 4
for i in itertools.repeat(None, 4):
    print("Loop iteration")
Loop iteration
Loop iteration
Loop iteration
Loop iteration

Here, we are iterating a loop N(4) times and printing a message in each iteration. We are using the repeat() method of itertools module. You need to import it before using the repeat() method.

This is the fastest way to loop N times in python. There are more methods to do the same. We are also listing them with examples here.

Why do we run a loop N times in python?

Sometimes, we don't have any list or sequence but want to execute some expressions N time then you can use this approach to rum a for loop N times and execute the statements in each iteration.

Search Index Data (The code snippet can also be found with below search text)

python loop n times
N = 4
for i in range(N):
  print("Iteration", i)

# Output
# Iteration 0
# Iteration 1
# Iteration 2
# Iteration 3
We can also use the range() function to loop N times in python. We can also get iteration index using range() method in for loop.
Was this helpful?
Programming Feeds
Learn something new everyday on Devsheet