5
import numpy as np

a = np.eye(2)
b = np.array([1,1],[0,1])

my_list = [a, b]

a in my_list returns true, but b in my_list returns "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()". I can get around this by converting the arrays to strings or lists first, but is there a nicer (more Pythonic) way of doing it?

2 Answers 2

3

The problem is that in numpy the == operator returns an array:

>>> a == b
array([[ True, False],
       [ True,  True]], dtype=bool)

You use .array_equal() to compare arrays to a pure boolean value.

>>> any(np.array_equal(a, x) for x in my_list)
True
>>> any(np.array_equal(b, x) for x in my_list)
True
>>> any(np.array_equal(np.array([a, a]), x) for x in my_list)
False
>>> any(np.array_equal(np.array([[0,0],[0,0]]), x) for x in my_list)
False
Sign up to request clarification or add additional context in comments.

2 Comments

Is the reason why it succeeds if I check the first value (as in a in my_list above) due to short-circuiting: if every element in the array is true on the first check it doesn't check the rest of the list?
@ChrisMidgley: Yes it is short-circuiting (the any() function is short-circuiting too, btw). Also, if all elements are True, it is unambiguous that the boolean value is True. But if it's a mix of True and False then NumPy can't decide the implicit conversion, thus raising an Error.
-1

More info about the problem. If you form my_list with

my_list = [b,a] 

the one that fails is a... Interesting problem.

1 Comment

If you want to know about why, check out the documentation of/google PyObject_RichCompareBool.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.