Idiom for consecutive loops?

Aahz Maruch aahz at
Wed Aug 8 17:35:32 CEST 2001

In article <yv2wv4hqtkw.fsf at>,
Harald Kirsch  <kirschh at> wrote:
>When programming in C I find myself writing consecutive loops like
>  for(i=3D0; i<lastI; i++) {
>    justDoIt(i);
>    if( someTest(i) ) break;
>  }
>  /* the next loop continues were the last one stopped */
>  for(/**/; i<lastI; i++) {
>    doSomethingElse(i);
>  }       =

Here's how I'd do it:

flag = None
for item in l:
    if flag is None:
        if someTest(item):
            flag = 1

I suppose that technically it's slightly more inefficient because you're
testing flag on every loop iteration, but it's almost certainly the case
that it'll be swamped by the time for justDoIt() and doSomethingElse().
And I think that the algorithm is *much* clearer by using only one loop.
                      --- Aahz  <*>  (Copyright 2001 by aahz at

Hugs and backrubs -- I break Rule 6       
Androgynous poly kinky vanilla queer het Pythonista   

"activist for accuracy"  --SJM

More information about the Python-list mailing list