2
for x in range(len(pallets_data_list)):
    """
    SOME CODE
    """
    if pallets_data_list[x]['data_id'] == 32:
        # Go back and search again in for loop

In above code, I have a for loop which is iterating over pallets_data_list. Inside this for loop, if the condition becomes True, I need to go back to for loop and start iterating again from 0. Lets consider that the condition becomes True at x = 20.

To reset x, I am setting it to 0 and then using continue like below:

    if pallets_data_list[x]['data_id'] == 32:
        # Go back and search again in for loop
        x = 0
        continue

Using continue, its going back to for loop but x is not reset and starts iterating from 21. Is there any way, I can reset x again back to 0. Can anyone please suggest any good solution. Please help. Thanks

S Andrew
  • 5,592
  • 27
  • 115
  • 237
  • Does this answer your question? [python: restarting a loop](https://stackoverflow.com/questions/492860/python-restarting-a-loop) – b-fg Apr 10 '20 at 08:42

2 Answers2

3

Simply do not use a for loop but a while loop.

The following for loop (which does not work):

for i in range(n):
    ...
    if condition:
        i = 0

should be replaced by:

i = 0
while i < n:
    ...
    if condition:
        i = 0
    else:  # normal looping
        i += 1

or, with continue:

i = 0
while i < n:
    ...
    if condition:
        i = 0
        continue
    i += 1

When using while beware of possible infinite looping. Possible strategies to avoid infinite looping include using a flag or including an extra counter that limits the maximum number of iterations regardless of the logic implemented in the body.

norok2
  • 25,683
  • 4
  • 73
  • 99
  • and what is `n` here in while loop – S Andrew Apr 10 '20 at 08:54
  • @SAndrew Sorry I thought it was clear from the "equivalent except not working `for` loop". `n` is the argument of `range()` in the `for` loop code, i.e. the number of times the loop would execute should the `condition` never be `True`. – norok2 Apr 10 '20 at 09:17
3

You need to be careful not to create an infinite loop by resetting the index. You can use a while loop with a found flag to avoid that:

pallets_data_list = [1, 4, 6, 32, 23, 14]

x = 0
found = False
while x < len(pallets_data_list):
    print(pallets_data_list[x])
    if not found and pallets_data_list[x] == 32:
        found = True
        x = 0
        continue
    x += 1

Output:

1
4
6
32
1
4
6
32
23
14
Nick
  • 138,499
  • 22
  • 57
  • 95