What does 'a' and 'b'
in Python mean and why does it equal 'b'
? Why does it not equal 'a'
?
>>> 'a' and 'b'
'b'
What does 'a' and 'b'
in Python mean and why does it equal 'b'
? Why does it not equal 'a'
?
>>> 'a' and 'b'
'b'
From the Pycharm docs:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
Because 'a' is not False 'b' is evaluated and returned.
Also nice to know. What is evaluated as True and what as False:
the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
Either 'a'
or 'b'
would be an acceptable answer to 'a' and 'b'
(since both are truthy), but only False
would be an acceptable answer to 'a' and False
, just as only 0
would be an acceptable answer to 'a' and 0
(since the result of this evaluation must be false-y to be logically correct).
Having a short-circuiting boolean evaluation follow the right-hand path when the left-hand is true allows there to be a single rule that applies in all cases.