Python paradigms

David Goodger dgoodger at bigfoot.com
Sun Apr 9 17:42:25 EDT 2000


talking about C's "test ? true : false" operator,

on 2000-04-09 12:55, Emile van Sebille (emile at fenx.com) wrote:
> This construct has been occasionally suggested
> as one option:
> 
>>>> print ['falseresponse','truresponse'][1==2]
> falseresponse
>>>> print ['falseresponse','truresponse'][1==1]
> truresponse

There is a hidden pitfall here. You have to be careful with the test (used
as list index) at the end ("[1==2]" & "[1==1]" here). Whereas the comparison
operators (==, <, >=, etc.) will always return either 0 (false) or 1 (true),
more complex boolean operations involving "and" and/or "or" may not. For
example:

    print ['falseresponse','truresponse'][a and b]

The result depends on the values of a & b. If a is 0, fine, 'falseresponse'.
If a is an empty string, an empty list, etc. (all false-equivalent values),
you'll get an error. If a is non-zero or true-equivalent, the index will be
b's value, whatever that is. If b isn't either 0 or 1, you'll get an error
or unpredictable results.

You can of course avoid this by reversing the list and adding a "not" around
the boolean:

    print ['truresponse','falseresponse'][not(a and b)]

"not" always returns 0 or 1.

See section 5.10 of the Python Reference Manual, "Boolean operations".

-- 
David Goodger    dgoodger at bigfoot.com    Open-source projects:
 - The Go Tools Project: http://gotools.sourceforge.net
 (more to come!)




More information about the Python-list mailing list