[Numpy-discussion] what does "in" do with numpy arrays?

Christopher Barker Chris.Barker at noaa.gov
Tue May 31 12:25:04 EDT 2011


Hi folks,

I've re-titled this thread, as it's about a new question, now:

What does:

something in a_numpy_array

mean? i.e. how has __contains__ been defined?

A couple of us have played with it, and can't make sense of it:

> In [24]: a
> Out[24]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
>
> In [25]: 3 in a
> Out[25]: True
>
> So the simple case works just like a list. But what If I look for an array in another array?

> In [26]: b
> Out[26]: array([3, 6, 4])
>
> In [27]: b in a
> Out[27]: False
>
> OK, so the full b array is not in a, and it doesn't "vectorize" it,
> either. But:
>
> In [29]: a
> Out[29]:
> array([[ 0,  1,  2],
>          [ 3,  4,  5],
>          [ 6,  7,  8],
>          [ 9, 10, 11]])
>
> In [30]: b in a
> Out[30]: True
>
> HUH?
>
> I'm not sure by what definition we would say that b is contained in a.
>
> but maybe..
>
> In [41]: b
> Out[41]: array([  4,   2, 345])
>
> In [42]: b in a
> Out[42]: False
>
> so it's "are all of the elements in b in a somewhere?" but only for 2-d
> arrays?
>
>
> So what does it mean?
>
> The docstring is not helpful:
>
> In [58]: np.ndarray.__contains__?
> Type:		wrapper_descriptor
> Base Class:	<type 'wrapper_descriptor'>
> String Form:	<slot wrapper '__contains__' of 'numpy.ndarray' objects>
> Namespace:	Interactive
> Docstring:
>       x.__contains__(y)<==>  y in x

On 5/29/11 2:50 PM, eat wrote:
> FWIW, a short prelude on the theme seems quite promising, indeed:
> In []: A
> Out[]:
> array([[0, 1, 2],
>         [3, 4, 5],
>         [6, 7, 8]])
> In []: [0, 1, 2] in A
> Out[]: True
> In []: [0, 3, 6] in A
> Out[]: True
> In []: [0, 4, 8] in A
> Out[]: True
> In []: [8, 4, 0] in A
> Out[]: True
> In []: [2, 4, 6] in A
> Out[]: True
> In []: [6, 4, 2] in A
> Out[]: True
> In []: [3, 1, 5] in A
> Out[]: True
> In [1061]: [3, 1, 4] in A
> Out[1061]: True
> But
> In []: [1, 2, 3] in A
> Out[]: False
> In []: [3, 2, 1] in A
> Out[]: True
>
> So, obviously the logic behind __contains__ is not so very
> straightforward. Perhaps just a bug?

-Chris



-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov



More information about the NumPy-Discussion mailing list