Idiom for consecutive loops?

Aahz Maruch aahz at panix.com
Wed Aug 8 11:35:32 EDT 2001


In article <yv2wv4hqtkw.fsf at lionsp093.lion-ag.de>,
Harald Kirsch  <kirschh at lionbioscience.com> 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:
        justDoIt(item)
        if someTest(item):
            flag = 1
    else:
        doSomethingElse(item)

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 pobox.com)

Hugs and backrubs -- I break Rule 6                 http://www.rahul.net/aahz/
Androgynous poly kinky vanilla queer het Pythonista   

"activist for accuracy"  --SJM



More information about the Python-list mailing list