3
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

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

and what is n here in while loop
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.