0

Possible Duplicate:
Python: Continuing to next iteration in outer loop

Maybe the title is kind of confusing but you will understand what i mean in the code:

for item in items: #i want to skip one loop of this bucle
    for i in item: #loop nº2
        if i==5:
            continue #but this only skip a loop in nº2, there's no propagation

How can i get this to work? Thanks in advance.

Community
  • 1
  • 1
jack-all-trades
  • 282
  • 1
  • 4
  • 18

1 Answers1

4

Set a flag, break out of the inner loop, check the flag in the main loop, and continue as appropriate.

  for i = 1 to N do
     flag = false
     for j = 1 to M do
        ...
        if condition then
           flag = true
           break
        ...
     if flag then continue
     ...
Patrick87
  • 27,682
  • 3
  • 38
  • 73
  • Yep, that should work, but i thought that maybe there was another more-pythonic way... – jack-all-trades Jul 23 '11 at 14:40
  • 1
    In general, I'd recommend you not worry about what is "Pythonic". – Patrick87 Jul 23 '11 at 14:42
  • @Thomas: Quite the contrary, I'd highly recommend learning idioms and applying them whenever sensible. (Of course there are also claims of this or that being "pythonic" that are at least fishy.) –  Jul 23 '11 at 14:49
  • The issue that "break" can only exit the innermost while/for loop comes up periodically. From what I've gathered, all the solutions proposed to date have been somewhat complex, requiring core modifications to the grammar, which the Python dev team has deemed "not worth it" given the comparative rarity of the use-case. So Thomas's solution is in fact the commonly accepted way to go, as aesthetically unpleasing as it is :) – Eli Collins Jul 23 '11 at 14:50
  • Of course not, but when i start using some code-tricks like this.. at the end the code becomes anything but human-readable.. hehe And it's a pain if you have to perform some improvements after a year – jack-all-trades Jul 23 '11 at 14:50
  • You're asking about an irreducibly complex control flow construct. If you want cleaner code, restructure it so breaks/continues are not necessary. – Patrick87 Jul 23 '11 at 14:54
  • Im parsing tables in HTML with lxml, so they are like a matrix; what i need is jump to the next line, not the next column, when a flag is found. And there's the easiest way i found to do it – jack-all-trades Jul 23 '11 at 15:04
  • 1
    What you can do in that case is break out the parsing of the table cell (which I gather involves some kind of loop) into its own function, which returns the flag (or raises an exception). – kindall Jul 23 '11 at 15:26