Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical operation between two Boolean lists

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?

like image 324
Yohan Obadia Avatar asked Nov 21 '17 17:11

Yohan Obadia


3 Answers

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)
like image 99
jasonharper Avatar answered Oct 18 '22 10:10

jasonharper


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.

like image 7
Patrick Haugh Avatar answered Oct 18 '22 10:10

Patrick Haugh


I think you need something like this:

[x and y for x, y in zip([True, False, False], [True, True, False])]
like image 4
AyumuKasuga Avatar answered Oct 18 '22 09:10

AyumuKasuga