which for loop in a nested for loop will we close first? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

which for loop in a nested for loop will we close first?

for a in list1: for b in list2: if a==b: print(b) continue else: continue the first continue will take python to which of the two for loops?

7th Jan 2018, 8:03 AM
Bushra Ali
2 Answers
+ 6
The first 'continue' goes back to the 'for b' loop and so does the 'else: continue'. In fact, they are both redundant because that's what happens with an 'if' statement in a 'for' loop anyway: If the condition is true, the code block is run and then the if statement is run for the next iteration in the loop. If the condition is false, the block is not run and the if statement is run for the next iteration in the loop. All you need is: for a in list1: for b in list2: if a == b: print(b) You can visualize the execution step by step here: https://goo.gl/D63pxW
7th Jan 2018, 11:54 AM
David Ashton
David Ashton - avatar
+ 4
The inner loop (for b in list2) I suppose, the condition checking of a==b is performed inside the inner loop. The continue statement will make the Python jump to the next iteration of the inner loop. Hth, cmiiw
7th Jan 2018, 8:34 AM
Ipang