multiple breaks

Peter Otten __peter__ at web.de
Thu Nov 13 06:15:43 EST 2008


TP wrote:

> Hi everybody,
> 
> Several means to escape a nested loop are given here:
> 
>
http://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python
> 
> According to this page, the best way is to modify the loop by affecting
> the variables that are tested in the loops. Otherwise, use exception:
> 
> "If, for some reason, the terminating conditions can't be worked out,
> exceptions are a fall-back plan."
> 
> In the following example, is this possible to affect the two iterators to
> escape the two loops once one "j" has been printed:
> 
> for i in range(5):
>     for j in range(i):
>        print j
>        # I would type "break 2" in shell bash
>        # In C, I would set j=i-1 and i=4
>        # In Python, is this possible to affect the two iterators?
> 
> Or the only means is to use exception?

Here's one way to turn multiple iterators into a single one:

def pairs(n):
    for i in range(n):
        for k in range(i):
            yield i, k

for i, k in pairs(5):
    print i, k

I've yet to see an example where a multi-level break would improve the
code's readability. It is typically a speed hack.

Peter

PS: Have a look into the itertools if you consider that approach.



More information about the Python-list mailing list