'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

后端 未结 8 779
别那么骄傲
别那么骄傲 2020-11-22 07:56

What explains the difference in behavior of boolean and bitwise operations on lists vs NumPy arrays?

I\'m confused about the appropriate use of

8条回答
  •  天涯浪人
    2020-11-22 08:47

    1. In Python an expression of X and Y returns Y, given that bool(X) == True or any of X or Y evaluate to False, e.g.:

      True and 20 
      >>> 20
      
      False and 20
      >>> False
      
      20 and []
      >>> []
      
    2. Bitwise operator is simply not defined for lists. But it is defined for integers - operating over the binary representation of the numbers. Consider 16 (01000) and 31 (11111):

      16 & 31
      >>> 16
      
    3. NumPy is not a psychic, it does not know, whether you mean that e.g. [False, False] should be equal to True in a logical expression. In this it overrides a standard Python behaviour, which is: "Any empty collection with len(collection) == 0 is False".

    4. Probably an expected behaviour of NumPy's arrays's & operator.

提交回复
热议问题