Logical operators operate on the truthiness of an object. Every object has truth value, unless it has a __bool__
method that is explicitly overridden to raise an error. The major difference between a and b
(logical) and a & b
(bitwise) is that the former apply to any objects, while the latter only apply to numeric types that support bitwise operations1.
Python's logical operators are specifically designed to return the result of the last object evaluated:
a and b
: Returns a Falsy a
, or b
(if a
is truthy)
a or b
: Returns a Truthy a
, or b
(if a
if falsy)
From the tutorial:
The Boolean operators and
and or
are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A
and C
are true but B
is false, A and B and C
does not evaluate the expression C
. When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.
This property is used semi-idiomatically to check values before accessing them. For example, if a list must contain an element, you can do something like
if x and x[0] == value:
# ...
This will not raise an error, because if x
is Falsy (empty), the and
expression will return x
instead of x[0] == value
.
1 Set-like objects also support &
as the intersection operator. This is conceptually similar to what the bitwise operator does for integers (you can think of bits as sets), and in no way detracts from the rest of the answer.