how can this iterator be optimized?

Basilisk96 basilisk96 at gmail.com
Fri Feb 13 19:44:38 EST 2009


On Feb 12, 1:15 am, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> 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



More information about the Python-list mailing list