1

I have the following code:

   def getEmptySquares(self):
        emptySquares=deque([])
        for i in range(self.grid.shape[0]):
            for j in range(self.grid.shape[1]):
                if np.array([i,j]) not in dequeList:
                    emptySquares.append(np.array([i,j]))
        print(emptySquares)

where the grid is a numpy array.

An example of the dequeList variable is:

deque([array([5, 7]), array([6, 7]), array([6, 6]), array([6, 5]), array([6, 4]), array([5, 4])])

I get the following error when I run this function:

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

Why is this happening?

KaneM
  • 259
  • 2
  • 9
  • Does this answer your question? [ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()](https://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous) – AMC Mar 02 '20 at 16:38
  • @AMC While there is some overlap between the two questions, the question you linked does not address why this error occurs in the context of the OP's question, i.e. when searching for an array within a collection. – Brian61354270 Mar 02 '20 at 16:48

1 Answers1

1

The issue you're running into here is that numpy does not define __eq__ for np.arrays as a comparison, but rather a method to construct a "logical" array.

Consider the array:

some_array = np.array([1, 2, 3, 4])

What do you expect the value of some_array == some_array will be? Usually in Python, we would expect it to be True, but this is not the case in numpy:

>>> some_array == some_array
array([True,  True, True, True])

Instead of boolean, using == with np.arrays produces another np.array. If we try to treat this array like a boolean, we get the error you encountered:

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

This error pops up here since checking whether or not an object is contained in a collections.deque involves iterating over the deque and comparing each element to the object in question. At each step, python calls the np.array.__eq__ method, and then "gets confused" when it receives an array instead of a bool.

To mitigate this, you need to manually search the deque for the array in question rather than relying on the in operator. This can be accomplished by applying the any builtin to a generator which performs the element-wise comparisons:

new_array = np.array([i,j])
if not any((new_array == elem).all() for elem in dequeList)):
   ...
Brian61354270
  • 8,690
  • 4
  • 21
  • 43