moving on to the next condition within a loop after the previous condition is met

Viewed 71

I try to iterate j over the first condition. Only if the first if-statement is not true for every j in range(5) then I want j to iterate over the next condition.

General problem:

my_list = []
    for i in range(3):
        for j in range(5):
            if #condition == True:
                 #append something to my_list for only one j in range(5)
                 break # move on to the next i
            elif #other condition == True:
                 #append something to my_list for only one j in range(5)
                 break # move on to the next i

Example:

my_list = []
for i in range(3):
    for j in range(5):
        if j == 3:
            my_list.append(j)
            break
        elif j == 0:
            my_list.append(j)
            break         
my_list

Output: [0, 0, 0]

What I want as output: [3, 3, 3]

1 Answers

The expected logic is not fully clear, but IIUC, you want to achieve a mechanism where your use one condition until it is met, then change to another one?

You can maybe use a single comparison with a list holding the conditions?

my_list = []
for i in range(3):
    conds = [3,0]       # list of conditions
    cond = conds.pop(0) # start with first one
    for j in range(5):
        if j == cond:   # if condition is met
            my_list.append(j) # store value
            if conds:   # if conditions are remaining
                cond = conds.pop(0) # use the next one
            else:       # else terminate the sub-loop
                break

output: [3, 3, 3]

Related