Why does '' and not '123' evaluate to '' instead of False, but not '123' and '' evaluates to False in Python 3.4.3?
1 Answer
The logical and/or operators stop evaluating terms (short-circuit) as soon as the answer is decided.
Examples with and
>>> '' and not '123'
''
The first one is false, so the and is short-circuited and the first one is returned.
>>> not '123' and ''
False
not '123' returns False. Since that is false, the and is short-circuited and the result of not '123' one is returned.
For exactly the same reason, the following returns zero:
>>> 0 and '123'
0
And the following returns []:
>>> [] and '123'
[]
Examples with or
>>> '' or '123'
'123'
>>> not '123' or 'Hi'
'Hi'
>>> '123' or 'Hi'
'123'
Documentation
This behavior is specified in the documentation where:
x or yis defined asif x is false, then y, else xx and yis defined asif x is false, then x, else ynot xis defined asif x is false, then True, else False
3 Comments
x or y or z or 0 works like COALESCE(x, y, z, 0) in SQL. Awesome.or looks for the first argument that does not evaluate to False. I just added a link to the docs which may help.