Write Python. Understand every error.

Open the editor

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.

Try this code in Py-CRAFT

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

Learn the ideas behind it

Other common errors

Share this page: