Most compact "X if X else Y" idiom
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sun Oct 12 01:30:33 EDT 2008
On Sat, 11 Oct 2008 22:01:46 -0700, jbperez808 wrote:
> I find myself having to do the following:
>
> x = (some complex expression)
> y = x if x else "blah"
>
> and I was wondering if there is any built-in idiom that can remove the
> need to put (some complex expression) in the temporary variable x.
Use short-circuit Booleans:
y = x or "blah"
If x is any true value (non-zero number, non-empty string etc.) then y
will be set to x; but if x is any false value (zero, empty string, None,
empty list, etc.) then y will be set to "blah".
However, this technique doesn't work for arbitrary tests. For example,
you can't simplify the following:
x = (some complex expression)
y = x if 100<=x<250 else "blah"
(at least I can't think of any way).
--
Steven
More information about the Python-list
mailing list