Can someone explain why the following occurs? My use case is that I have a python list whose elements are all numpy ndarray objects and I need to search through the list to find the index of a particular ndarray obj.
Simplest Example:
>>> import numpy as np
>>> a,b = np.arange(0,5), np.arange(1,6)
>>> a
array([0, 1, 2, 3, 4])
>>> b
array([1, 2, 3, 4, 5])
>>> l = list()
>>> l.append(a)
>>> l.append(b)
>>> l.index(a)
0
>>> l.index(b)
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()
Why can l find the index of a, but not b?
numpyboolean array (or list). e.g.if [True,False...]:. Here I suspect oneindexmatches on ids, the other tries an==test. Seems to depend on how the list is constructed.numpyarrays are probably not a good idea.iscomparison first, if that fails python compares with==. The latter does not work on numpy arrays and gives you the error. Your code probably only works because the very firstiscomparison is already true and you don't ever invoke a==comparison in this case.aandbare different lengths, then no error occurs becausea == breturnsFalseinstead of a bool array.