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.