2
votes

I would like to assign to d either a or, if a is None, b or, if b is also None, c. This works:

a = b = c = np.array([1])
d = a or b or c

However, this does not:

a = b = c = np.array([1, 2])
d = a or b or c

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

Apparently, or is being used element-wise for arrays with more than one element. What can I do to achieve

d = a or b or c

with NumPy arrays?

1

1 Answers

6
votes

I would like to assign to d either a or, if a is None, b or, if b is also None, c.

Then literally check for None:

d = a if a is not None else b if b is not None else c

The fact that your version works for single-element arrays is a side-effect of their truthiness. It won't do what you expect with this:

a = np.array([0])
b = "wat"

c = a or b

c will now be "wat", even though a is not None.