Repeat N Times in Python

  1. Repeat N Times in Python Using the range() Function
  2. Repeat N Times in Python Using the itertools.repeat() Method

In this tutorial, we will look into various methods to repeat the code N times in Python. In many cases, we need to perform a set of actions on each element of an array, like processing text line by line, performing some mathematical operations on each value of an array or sorting an array or list, etc.

We need to repeat some portion of the code for all the tasks mentioned above again and again. This tutorial will look into different methods to repeat the specific task N times in Python.

Repeat N Times in Python Using the range() Function

The most common way to repeat a specific task or operation N times is by using the for loop in programming.

We can iterate the code lines N times using the for loop with the range() function in Python. The range(start,stop,step) function returns the sequence of numbers starting from the value specified in the start argument (equal to 0 by default), till the value specified in the stop argument. The step argument specifies the step size of the sequence returned by the range() function, and its value is set to 1 by default.

The below code example demonstrates how to create a for loop with the range() method to repeat the code N times:

num = 10
for x in range(num):
    #code

Suppose the variable x is not desired in the code; in that case, we can use the for loop in the following way. _ is used as a throwaway variable in the loop.

num = 10
for _ in range(num):
    #code

Repeat N Times in Python Using the itertools.repeat() Method

The itertools.repeat(val, num) method is an infinite iterator, which means it will iterate infinitely till the break statement if the num value (which represents the number of iterations) is not provided. The val parameter of this method represents the value that will be printed on each iteration.

As we want to repeat the iteration N times, we will pass the value of N to the num argument and None value to the val argument since we do not need to print anything. The itertools.repeat() method is more efficient than the range() method, but the itertools module needs to be imported to use this method.

The below code example demonstrates how to use the itertools.repeat() method to repeat a specific code N times:

import itertools

num = 10
for _ in itertools.repeat(None, num):
    #code
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Loop

  • One Line for Loop in Python