I get a weird result and I try to apply the and
or the or
operator to 2 Boolean lists in python. I actually get the exact opposite of what I was expecting.
[True, False, False] and [True, True, False]
> [True, True, False]
[True, False, False] or [True, True, False]
> [True, False, False]
Is that normal, and if yes, why?
If what you actually wanted was element-wise boolean operations between your two lists, consider using the numpy
module:
>>> import numpy as np
>>> a = np.array([True, False, False])
>>> b = np.array([True, True, False])
>>> a & b
array([ True, False, False], dtype=bool)
>>> a | b
array([ True, True, False], dtype=bool)
This is normal, because and
and or
actually evaluate to one of their operands. x and y
is like
def and(x, y):
if x:
return y
return x
while x or y
is like
def or(x, y):
if x:
return x
return y
Since both of your lists contain values, they are both "truthy" so and
evaluates to the second operand, and or
evaluates to the first.
I think you need something like this:
[x and y for x, y in zip([True, False, False], [True, True, False])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With