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

Just van Rossum just at letterror.com
Wed Aug 8 14:28:13 EDT 2001


[me]

> >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)
 
[Aahz]
> Someone else suggested this;

Ah, I see: I missed that one.

> 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.

Hm, I'm not sure I agree with that: your suggested flag isn't all that
clear either, and I don't see the iterator version as an optimization.
I could argue just as well that the iterator version is clearer as it
clearly shows what is done first and what is done later. It's also a
fine example of how powerful iterators are. And sure, it's only clear
if you *understand* iterators, but that wouldn't be a good argument
against it.

Either way, it depends on what exactly you're doing which might be better
or clearer. Dismissing the iterator version as a "Bad Idea" is IMO in
itself a "Bad Idea" ;-)

Just



More information about the Python-list mailing list