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

Paul F. Dubois dubois at users.sourceforge.net
Fri Feb 7 23:36:31 EST 2003


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 did raise the question in my mind about whether or not I could just
put:
y = [sqrt(z) if z > 0.0 else 0.0 for z in x]

I don't remember the precedence of the 'for' here. It would be good if this
is correct.











More information about the Python-list mailing list