how can this iterator be optimized?

josh logan dear.jay.logan at
Sat Feb 14 16:03:54 CET 2009

On Feb 13, 7:44 pm, Basilisk96 <basilis... at> wrote:
> On Feb 12, 1:15 am, Steven D'Aprano
> <ste... at> wrote:
> > > I usually strive
> > > for comprehensions if a for loop can be reduced to such.
> > Any particular reason?
> Only two.
> 1.) I was impressed by their clarity and conciseness when I first
> discovered them.
> 2.) I also read now and then that simple list comprehensions are
> faster when compared with their for-loop equivalents because of the
> way comprehensions are implemented under the hood. My example is a far
> cry from a "simple" comprehension, however. :)
> > If there's only one call to func(), and you ignore the (probably) fixed
> > cost of jumping into a generator each time, then it shouldn't make any
> > difference.
> > If you are comparing one call to func() in a for loop versus three calls
> > to func() in a list comp or generator expression, then of course the for
> > loop will be more efficient.
> I agree. I would rather call func() only once per iteration in any
> case. I will revise it to a plain for loop with a single call.
> Thanks,
> -Basilisk96

Just as long as you do realize that it is possible to do what you were
looking with one call to func() using chained generators, as
demonstrated in my post above. Whichever way is clearest for you would
be the way I'd go.

More information about the Python-list mailing list