In Python, an empty list is considered a Falsey value
Therefore this is how things should work:
>>> [] and False
False
But in reality, python returns an empty list.
>>> [] and False
[]
Is this intended or a bug?
CodePudding user response:
It's intended. Both and
and or
are defined to return the last thing evaluated (based on short-circuiting), not actually True
or False
. For and
, this means it returns the first falsy value, if any, and the last value (regardless of truthiness) if all the others are truthy.
It was especially useful back before the conditional expression was added, as it let you do some almost-equivalent hacks, e.g. before the conditional expression:
b if a else c
could be written as:
a and b or c
and, assuming b
itself was some truthy thing, it would behave equivalently (the conditional expression lacked that limitation and was more clear about intent, which is why it was added). Even today this feature is occasionally useful for replacing all falsy values with some more specifically-typed default, e.g. when lst
might be passed as None
or a list
, you can ensure it's a list
with:
lst = lst or []
to cheaply replace None
(and any other falsy thing) with a new empty list
.
CodePudding user response:
This is how it is supposed to work. and
will only return the right hand operand if the left hand operand is truthy. Since []
is falsy, and
returns the left hand operand.
CodePudding user response:
This is intended behavior and not a bug. In Python, the truthiness of an object is determined by the built-in bool()
function, which returns False for empty sequences (such as empty lists, tuples, and strings) and zero of any numeric type. However, when used as the operands of the and
operator, the operands are not converted to booleans, but instead their actual values are used. So in this case, the and
operator is not checking for truthiness, but instead it is returning the first falsey value it encounters, which in this case is an empty list, so it returns an empty list.
CodePudding user response:
That's a totally expected behaviour. To understand it, you need to know how the Boolean operators (and
, or
, not
) work. From the Boolean Operations documentation:
The expression
x and y
first evaluatesx
; ifx
is false, its value is returned; otherwise,y
is evaluated and the resulting value is returned.
Now let's consider your example: [] and False
. Here, since []
is falsey, it's value is returned back by the statement which is []
.
Above linked Python documentation explicitly mentions:
Note: Neither
and
noror
restrict the value and type they return toFalse
andTrue
, but rather return the last evaluated argument.
However, in case you need the return value as boolean, you can explicitly type-cast the value to True
or False
using the bool()
function.
For example, in your case it will return as False:
>>> bool([] and False)
False