0
For Loop Iteration Skip
hello - I need some help in how to skip the iteration of a for loop within loops, Example, I have 2 for loops one within the other as below, for i in range(0, 10): for j in range(0,10): if x[i] == y[j]: result = y[j] break All I want to achieve is, for example, if i = 0, then j loop runs from 0 - 9, If my condition x[i] == y[j] matches at j = 5, then i should break the loop(skip i = 0 & J = 6,7,8,9) and start over from i = 1 but j = 6.. I tried with break.. but with break, j starts from 0 instead of 6.. i want to start the loop with i = 1 and j = 6 if x[i] == y[j]. please let me know your thoughts.
7 Answers
+ 7
j will not become 6 because value of j is fixed in range from 0 to 4.
So make range(0,10)
When you are using break statement, second for loop breaks and due to first for loop it start again from 0.
So if you want to continue second for loop use continue statement instead of break.
#your code be like
for i in range(0, 10):
for j in range(0,10):
if x[i] == y[j]:
result = y[j]
continue
+ 3
maybe something like this?
k = 0
for i in range(0, 10):
for j in range(k,10):
if x[i] == y[j]:
result = y[j]
k = j
break
+ 2
well it doesnt sound like you want to break out of the second loop, but increment the first loop variable:
if x[i] == y[i]
result = y[j]
i = i+1
continue
+ 2
you should then add a check to see if i is still within the range at the start of the second loop
if i>=10
break
+ 1
NG_ break statement is used to break execution of loop and execute another executable statement outside the loop.
In your case if if condition is returned true then it will break the loop at that point then increase the value of i and continue execution of code with j=0.
Also if you want to take values of j from 0-9 change its range.
You can rather use continue statement instead of break.....
+ 1
You can do what you want with help of an extra variable and an else clause for the inner loop (see code)
Still i am not sure of the aim for this. What do you want the result to be? Not in terms of the code operation but in terms of values -- 'last element of y array that has a same element in x array' or something like that. Maybe then there is a simpler way to write the code you want.
https://code.sololearn.com/cG9eTEmODBHl/?ref=app
0
sorry my bad, I made a mistake in posting the code.. it should be for j in range(0,10):
but I still need to achieve j = 6 and i = 1 when the condition inside for loop is true.
can we do that?