Home > database >  Change the start point of a for loop
Change the start point of a for loop

Time:12-26

data = [a,b,c,d,e,f,g]

This is just an example of the information i am using.

I am having trouble with 2 things.

Scenario....

for x in data... .... do a bunch of stuff. break but it breaks at lets say "e" index # 4 when the loop starts back over how do i get it to start on index #5 ('f') and then finish #6 (g) but start back at #0 (a)

I am suppose to set an index number outside the loop.

So data_index = 0 then somewhere i have to put data_index =1 so that everytime it breaks it increases the data_index 1 until it reaches index #6 at which point in needs to revert back to #0

I feel like i know what to do but i cant seem to get the code line (for x in data) correctly written to do anything else.

CodePudding user response:

You can do the external data_index, and to make sure it doesn't break you can use a %, and it when looping through the array, accessing the correct index would be something like

data[data_index % len(data)]

CodePudding user response:

You can try this:

data = ...
idx = 0
# The first time
for x in data[idx:]:
    # Do whatever you intended to do 
    idx  = 1
    if ...:
        break

# The 2nd time
idx = idx % len(data)
for x in data[idx:]:
    # Do whatever you intended to do 
    idx  = 1
    if ...:
        break
  • Related