Saturday, 4th December 2010
And + or
or work in a slightly unusual way, which means they can be used to assign values.
Rather than write:
if n < 0: result = 'n is negative' else: result = 'n is positive'
You can write:
result = n < 0 and 'n is negative' or 'n is positive'
The result is shorter, though I'm not sure it's more readable. However, the fact that it's a single line makes it more versatile. For example, you can include it in a list comprehension, as I did in this contrived example, or you can pass it as an argument to a function.
Then general form is:
result = test and true_result or false_result
The logic is that the two results count as being true, so if the test is true, then test and true_result is true; if the test is false then test or false_result is true.
There is a more detailed explanation of why this trick works at Dive Into Python.