Two questions about efficiency
Fredrik Lundh
fredrik at pythonware.com
Wed May 26 17:02:08 EDT 2004
"Steve M" wrote:
> 2. Is there any reason to prefer one of the following over the other?
> Im interested in both a consensus on style and readability, and
> considerations of efficiency at runtime.
>
> for x in L:
> if f(x):
> pass
>
> for x in L:
> if f(x):
> continue
did you really mean to write that?
as written, both constructs are pointless, and the "if f(x)"-statement can
be replaced with just "f(x)" in both cases. and if you add more code inside
the if statement, or after it, the constructs do different things.
did you perhaps mean:
for x in L:
if f(x):
do stuff
for x in L:
if not f(x):
continue
do stuff
if so, my rule of thumb is to use alternative 1 if "stuff" is short, and alter-
native 2 if "stuff" is long, or if you have multiple tests before you get to
the real stuff.
ymmv, as usual.
and yes, if "stuff" is trivial, and builds a new list, consider using a list
comprehension:
L2 = [stuff for x in L if f(x)]
</F>
More information about the Python-list
mailing list