3

Below is a short piece of code that for some reason keeps generating the following value error message: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

import numpy as np
p=np.array([1,2,3])
q=np.array([4,5,5])

while p + q==7:
        try:
            assert p.any()
            assert q.any()
        except AssertionError:
            print('(p + q)<=6')
        print  (p + q)

I have tried both p.any and p.all, still getting the same error message. Any suggestions? Thanks.

1 Answer 1

4

Your problem is that p and q have three elements each, so p + q == 7 will also have three elements. For the while loop, you need something that can be interpreted as True or False - the error is telling you that three elements can't be interpreted as True or False without more information: it's ambiguous. If you want all of the elements to be equal to 7, use

while np.all(p + q == 7):

if you want any of them to be equal, use

while np.any(p + q == 7):
5
  • 2
    Alternatively, do exactly what the error message suggests: while (p + q == 7).any(): etc. Commented Aug 23, 2013 at 8:20
  • For me, the function scans closer to English than the method in this case ("while all elements equal to 7"). Commented Aug 23, 2013 at 8:22
  • I was mainly trying to give a hint what the error message means. Commented Aug 23, 2013 at 8:24
  • Hi all, thanks for your suggestions. I actually made used of (p + q==7).any(), but I placed it inside the try and except statement.
    – Tiger1
    Commented Aug 23, 2013 at 8:28
  • Another remark: the error gave you a line number (line 5 if your code is exactly the same) but you looked 2 lines down. Read carefully the error messages next time, they give precise indications about the problem. Commented Aug 23, 2013 at 12:17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.