Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continue in nested loops in Python

Tags:

python

How can you continue the parent loop of say two nested loops in Python?

for a in b:     for c in d:         for e in f:             if somecondition:                 <continue the for a in b loop?> 

I know you can avoid this in the majority of cases but can it be done in Python?

like image 425
James Avatar asked Feb 12 '13 09:02

James


People also ask

What is the syntax for a nested while loop in Python?

The syntax for a nested while loop statement in Python programming language is as follows − while expression: while expression: statement (s) statement (s) A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa.

What happens when you continue a loop in Python?

In Python, when the continue statement is encountered inside the loop, it skips all the statements below it and immediately jumps to the next iteration. In the following example, we have two loops. The outer for loop iterates the first list, and the inner loop also iterates the second list of numbers.

How to use one loop inside another loop in Python?

Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept. The syntax for a nested while loop statement in Python programming language is as follows − A final note on loop nesting is that you can put any type of loop inside of any other type of loop.

What is nested loop in C++?

If a loop exists inside the body of another loop, it is termed as Nested Loop. This means that we want to execute the inner loop code multiple times. The outer loop controls how many iterations the inner loop will undergo.


Video Answer


1 Answers

  1. Break from the inner loop (if there's nothing else after it)
  2. Put the outer loop's body in a function and return from the function
  3. Raise an exception and catch it at the outer level
  4. Set a flag, break from the inner loop and test it at an outer level.
  5. Refactor the code so you no longer have to do this.

I would go with 5 every time.

like image 158
Duncan Avatar answered Sep 28 '22 11:09

Duncan