import itertools
N = 4
for i in itertools.repeat(None, 4):
print("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.
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.
N = 4
for i in range(N):
print("Iteration", i)
# Output
# Iteration 0
# Iteration 1
# Iteration 2
# Iteration 3
0 Comments