I have encountered a behavior of the in
operator in the context of numpy arrays which I don’t understand.
>>> a=[0,1,2]
>>> x=np.array([a])
>>> b=[3,4,5]
>>> np.append(y,[b],axis=0)
array([[0, 1, 2],
[3, 4, 5]])
>>> a in x
True
>>> b in x
False
My motivation is to build a list of distinct vectors, so I need to be able to use the in
operator, and I need a way to extend my list of vectors so that an appended element is also seen as being in the list.
For my list I use a numpy array because the in
operator doesn’t work the way I expect.
So my questions here are:
- in the above example, why is
b
not seen as an element ofy
? - how can I append a numpy array to a numpy array of numpy arrays so that the
in
operator works as expected? - is there a better way to store vectors (i.e. numpy array of size 3), to that I can add new vectors, and such that the
in
operator sees newly added vectors as being elements of the structure?
2
np.append
does not modify the array in place. It creates a new array containing b
as the second row, but x
remains the same.
>>> np.append(x,[b],axis=0)
array([[0, 1, 2],
[3, 4, 5]])
>>> x
array([[0, 1, 2]])
>>> b in np.append(x,[b],axis=0)
True
Also, in
makes no sense in the first place for NumPy arrays. row in two_d_array
doesn’t test whether row
is a row of two_d_array
. It gives you (row == two_d_array).any()
, which for a 1D row
and a 2D two_d_array
, tests whether any element of row
shows up as an element of the corresponding column of two_d_array
.
1