# [SciPy-dev] "item in array" currently unsupported

Ed Schofield schofield at ftw.at
Thu Nov 17 11:50:58 CST 2005

```Hi all,

The ability to use the test "item in array" seems to be a casualty from
the recent change to newcore to raise an exception when interpreting
arrays as truth values.  The old Numeric would allow this:
>>> a = arange(100)
>>> a.shape = (10,10)
>>> a
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
>>> 0 in a
True
>>> -1 in a
False
>>> 100 in a
False
>>> 99 in a
True

newcore and numarray (1.4.1) raise an exception, requiring the use of
any() or all().  But the exception is bogus in this case: there's no way
to use any() or all() here.  Could we override __contains__ to do
something more useful?  I see two possibilities for the desired
behaviour.  One would be for "item in array" to return an array of truth
values.  But this doesn't seem feasible, since "item in obj" seems to
return only the truth value of whatever __contains__() returns.
(Another PEP candidate?)  The other is for __contains__ to do something
like this:

def __contains__(self, item):
if self.ndim > 1:
return item in self.ravel()
...

This is possible in numarray (using ravel(self)).  But this wouldn't
work in the current scipy core, which raises an exception for "0 in
a[0]" even if a[0] is a rank-1 array:

>>> 56 in a[0]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()

This last point seems to be a simple bug.  A simple test case is:

>>> 0 in arange(10)

which throws the same exception.

-- Ed

```