S Andrew
S Andrew

Reputation: 7218

How to reset the index number of for loop in python

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

Upvotes: 2

Views: 5530

Answers (2)

norok2
norok2

Reputation: 26886

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.

Upvotes: 3

Nick
Nick

Reputation: 147166

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

Upvotes: 3

Related Questions