Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean list operation in python [duplicate]

Shouldn't the results be the same? I do not understand.

[True,False] and [True, True]
Out[1]: [True, True]

[True, True] and [True,False]
Out[2]: [True, False]
like image 259
Tang Avatar asked Oct 19 '22 12:10

Tang


1 Answers

No, because that's not the way that and operation works in python. First off it doesn't and the list items separately. Secondly the and operator works between two objects and if one of them is False (evaluated as False 1) it returns that and if both are True it returns the second one. Here is an example :

>>> [] and [False]
[]
>>> 
>>> [False] and []
[]
>>> [False] and [True]
[True]

x and y : if x is false, then x, else y

If you want to apply the logical operations on all the lists pairs you can use numpy arrays:

>>> import numpy as np
>>> a = np.array([True, False])
>>> b = np.array([True, True])
>>> 
>>> np.logical_and(a,b)
array([ True, False], dtype=bool)
>>> np.logical_and(b,a)
array([ True, False], dtype=bool)

1. Here since you are dealing with lists an empty list will be evaluated as False

like image 115
Mazdak Avatar answered Oct 21 '22 06:10

Mazdak