Error guide · NumPy errors
ValueError: The truth value of an array with more than one element is ambiguous
An if or and was given a whole array of True and False values, and Python cannot decide which one to use.
Example
import numpy as np a = np.array([1, 5, 9]) if a > 3: print("big")
What Python says
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
As printed by Python 3.12. Other versions may word it slightly differently.
Why it happens
a > 3 gives one True or False for every element: [False True True]. An if needs a single answer. Ask the question you really mean: .any() for "at least one", .all() for "every element". To combine conditions on arrays, use & and | with brackets, not and and or.
How to fix it
import numpy as np a = np.array([1, 5, 9]) if (a > 3).any(): print("big")
Output: big
Tips
- Use
.any()or.all()to turn an array of answers into one answer. - Write
(a > 2) & (a < 8)instead ofa > 2 and a < 8. - To pick the elements that match, use a mask:
a[a > 3].