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 -- http://mail.python.org/mailman/listinfo/python-list