Search code examples
pythonnumpyexpressionbitwise-operatorscomparison-operators

What happens internally and raises ValueError while using bitwise and comparison operators with numpy arrays?


import numpy as np

arr = np.array([3, 4, 6, 15, 25, 38])


print(arr > 5 & arr <= 20)

"""Output
Traceback (most recent call last):
  File "main.py", line 11, in <module>
    print(arr > 5 & arr <= 20)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
"""

I know this error occurs because I have missed the parenthesis around conditions. But I want to know in which order the expression is evaluated and what causes this error.


Solution

  • & has a higher precedence than <=, so this is being run as arr > (5 & arr) <= 20 and since comparison operators are chained, this is the equivalent of:

    (arr > (5 & arr)) and (arr <= (5 & arr))
    

    And this causes the well known error because you cannot use arrays in a boolean context, as the error message explains... (Side note, 5 & arr is only evaluated once...)

    So consider, even this will fail:

    >>> arr = np.array([1,2,3,4,5])
    >>> 0 < arr < 4
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()