Idiom for consecutive loops?

Just van Rossum just at letterror.com
Wed Aug 8 11:55:21 EDT 2001


Aahz Maruch wrote:
> 
> 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.

FWIW, in Python 2.2 you could write:

it = iter(l)
for item in it:
    justDoIt(item)
    if someTest(item):
        break
for item in it:
    doSomethingElse(item)


Just



More information about the Python-list mailing list