Restart a Loop in Python

Restart a Loop in Python

In Python, we can use for loops and while loops to iterate over linear iterable data structures. We sometimes have to reset the iteration to the beginning during iteration, which is generally not recommended during manipulation. In this article, we will learn how to restart a for loop or a while loop in Python.

Restart a Loop in Python

Generally, loops are used to iterate over some linear data structure or run some piece of code n times. Now, to restart such a loop, we have to reset the iterator or the variable involved in the termination condition so that the loop continues to run. Consider a for loop. In for loops, we usually have an integer i, which iterates n times before its termination. So, to restart a for loop, we will manipulate the value of i. In Python, unfortunately, it is not possible to manipulate the for loop. In other languages, such as Java, C++, C, it is possible.

To get such behavior in Python, we can use a while loop. Refer to the following code. It has two variables, namely, i and n. i is the variable involved in the termination condition. Its value will be reset to 0 when the value of i gets more than or equal to n. The program implements an infinite loop to depict restarting.

i = 0
n = 10

while i < n:
    if i < 5:
        print(i)
        i += 1
    else:         
        i = 0 # This assignment restarts the loop

Output:

0
1
2
3
4
0
1
2
3
4
0
1
2
3
4
0
...
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

LinkedIn GitHub

Related Article - Python Loop

  • Access the Index in 'Foreach' Loops in Python
  • Python While Loop User Input
  • The Next Item in Python for Loop
  • Async for Loop in Python
  • Retry a Loop in Python
  • Skip Iterations in a Python Loop