Optimizing loops (was Re: Idiom for consecutive loops?)

Aahz Maruch aahz at panix.com
Wed Aug 8 14:07:21 EDT 2001


In article <3B7160E9.2450CBE7 at letterror.com>,
Just van Rossum  <just at letterror.com> wrote:
>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)

Someone else suggested this; I still think that using one for loop is
clearer, more understandable, and easier to maintain.  This particular
example really is *not* two for loops; it's one for loop that does two
different things depending on whether a sentinel has been hit.
Optimizing out the if into two loops is a Bad Idea IMO.
-- 
                      --- 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