For Loop Iteration Skip | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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.

9th Nov 2020, 3:38 AM
NG_
NG_ - avatar
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
9th Nov 2020, 3:49 AM
ツSampriya😘ツ
ツSampriya😘ツ - avatar
+ 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
10th Nov 2020, 5:04 PM
madeline
madeline - avatar
+ 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
9th Nov 2020, 4:54 AM
John Doe
+ 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
9th Nov 2020, 4:59 AM
John Doe
+ 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.....
9th Nov 2020, 4:13 AM
Sanjyot21
Sanjyot21 - avatar
+ 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
10th Nov 2020, 4:27 AM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar
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?
9th Nov 2020, 4:08 AM
NG_
NG_ - avatar