Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading