breaking out of outer loops

Antoon Pardon apardon at forel.vub.ac.be
Wed Feb 6 06:17:30 EST 2008


On 2008-01-29, Jeremy Sanders <jeremy+complangpython at jeremysanders.net> wrote:
> noemailplease0001 at gmail.com wrote:
>
>> Any elegant way of breaking out of the outer for loop than below, I
>> seem to have come across something, but it escapes me
>> 
>> for i in outerLoop:
>>    for j in innerLoop:
>>        if condition:
>>           break
>>    else:
>>        continue
>>     break
>
> Perhaps Python needs a "continue N" or a "break N" statement :-)
>
> for i in outerLoop:
>   for j in innerLoop:
>      if condition:
>         break 2

Just fake it with an exception

class LoopBreaker(Exception):
  pass

try:
  for i in outerLoop:
    for j in innerLoop:
      if condition:
        raise LoopBreaker
except LoopBreaker:
  pass

-- 
Antoon Pardon



More information about the Python-list mailing list