0

I was performing a code in python using for loop. But I want to restart the loop. How can I do this in for loop?

a=[some list]
z=len(a)
for i in range(z):
    if....:
        do something
    else:
        do some changes in "a"
        restart the loop from the beginning with i=0


How can I get there?

I don't have a clue actually on how to do this. I am very new to this.

  • 1
    Can you give some real, working code that's a bit closer to what you want? What kind of condition is in that `if....`? Could you put that condition in a `while` around the `for`? – Samwise Mar 03 '23 at 17:28
  • 4
    You have to wrap the for-loop in another loop, e. g. `while flag:`. When you want to restart the for-loop, set `flag` to `True` and `break` out of the for-loop. – Michael Butscher Mar 03 '23 at 17:28

2 Answers2

0

Use while loop instead of for loop

a = [1, 2, 3, 4, 5]
z = len(a)
i = 0

while i < z:
    if a[i] == 3:
        # do something
        i += 1
    else:
        # do some changes in "a"
        a[i] += 1
        i = 0
        continue
    i += 1
Jan
  • 302
  • 3
  • 5
0

Surround the for loop with a while loop, and break from that loop when the "restart" condition is not met.

Breaking from multiple loops is tricky. It is especially tricky in this case, because we only want to break the while loop if every element of the a list is valid. The most straightforward way to do this is to start the for loop with the assumption that every element is valid, and set a flag when an invalid element is found.

As a side note, iterating in Python is normally done directly, not with indices. for i in range(z) works by creating a sequence that the i values come from, and taking values from that sequence. If we want to use values that are in a, it is normally much simpler and cleaner to just... do that.

Putting these ideas together, we might get something like:

a = [1, 2, 3] # some initial value
done = False
while not done:
    for i in a:
        done = True
        if condition(i):
            do_something()
        else:
            done = False # make sure the `while` loop repeats
            a = modify(a)
            break # breaks the `for` loop, to prevent handling other `i` values
    # If we get past the `for` loop and `done` is still `True`, that means
    # that every element was valid. The `while` loop will also exit.
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153