2

I got an array of arrays:

temp = np.empty(5, dtype=np.ndarray) 
temp[0] = np.array([0,1])

I want to check if np.array([0,1]) in temp, which in the above example clearly is but the code returns false. I also tried temp.__contains__(np.array([0,1])) but also returns false. Why is this? Shouldn't it return true?

EDIT:

So __contain__ wont work. Is there any other way of checking?

user1234440
  • 22,521
  • 18
  • 61
  • 103
  • 3
    [Don't try to use `__contains__` in NumPy. It does crazy, useless shit.](http://stackoverflow.com/questions/18320624/how-does-contains-work-for-ndarrays) – user2357112 Dec 03 '13 at 02:47
  • so as of now the best solution is to iterate through the whole array to check each time? – user1234440 Dec 03 '13 at 02:52
  • numpy arrays with `dtype=object` are not very well developed. Basic things like indexing work. But binary operations are hit and miss. – hpaulj Dec 03 '13 at 04:01

1 Answers1

2

One thing you need to understand, in python in general, is that, semantically, __contains__ is based on __eq__, i.e. it looks for an element which satisfies the == predicate. (Of course one can override the __contains__ operator to do other things, but that's a different story).

Now, with numpy arrays, the __eq__ does not return bool at all. Every person using numpy encountered this error at some point:

if temp == temp2:
   print 'ok'
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Which means, given the conflicting semantics of the __contains__ and ndarray.__eq__, it's not surprising this operation does not do what you want.

With the code you posted, there is no clear advantage to setting temp to be a np.array over a list. In either case, you can "simulate" the behavior of __contains__ with something like:

temp2 = np.array([0,1])
any( (a == temp2).all() for a in temp if a is not None )

If you explain why you choose to use an hetrogeneous np.array in the first place, I might come up with a more detailed solution.

And, of course, this answer would not be complete without @user2357112's link to this question.

Community
  • 1
  • 1
shx2
  • 61,779
  • 13
  • 130
  • 153