Why do I have to use parantheses in (x > 0) & (x < 2) to avoid "The truth value of an array with more than one element is ambiguous"?

Having:

import numpy as np
x = np.ndarray([0,1,2])

This doesn’t work:

x > 0 & x < 2

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

This works:

(x > 0) & (x < 2)
Out[32]: array([False,  True, False])

So maybe the reason is operator precedence. But all of these work as well:

((x > 0) & x) < 2
Out[33]: array([ True,  True,  True])

(x > (0 & x)) < 2
Out[34]: array([ True,  True,  True])

x > ((0 & x) < 2)
Out[35]: array([False, False,  True])

x > (0 & (x < 2))
Out[36]: array([False,  True,  True])

Then why does the original expression not work, if any order of operator execution would work? Is it because choosing one of them is ambiguous? But then the exception message is misleading?

>Solution :

It seems that x > 0 & x < 2 is more like (x > (0 & x)) and ((0 & x) < 2), and the error is raised for the operation and.

I believe it’s caused by that & will be calculated before comparison, and python has a syntactic sugar to translate x > y < z into (x > y) and (y < z).

Leave a Reply