For review: PEP 308 - If-then-else expression

Anthony Baxter anthony at interlink.com.au
Sat Feb 8 01:01:50 EST 2003


>>> "Paul F. Dubois" wrote
> Two thumbs way up on 308.
> 
> Suppose x is a sequence of floats. Compare:
> 
> y = [0.0] * len(x)
> for i in range(len(x)):
>     if x[i] >= 0.0:
>         y[i] = sqrt (x[i])
> 
> vs.
> 
> y = [(sqrt(z) if z > 0.0 else 0.0) for z in x]
> 
> I think the second version is much easier to understand. It is a lot easier
> to write it without making a mistake. I'd guess it will turn out faster,
> too.

This might be fine, but if you start getting listcomps with one of
these ternary operators, and an if clause in the listcomp. you're 
going to be leaving someone with a hellish ugly bit of code to read.


Why not simply:

def condsqrt(z):
  if z > 0.0: 
    return sqrt(z)
  else:
    return 0.0

y = [ condsqrt(z) for z in x ]

There's a function call overhead, but it's a hell of a lot easier to
read.

Anthony





More information about the Python-list mailing list