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?

3
  • 3
    Don't try to use __contains__ in NumPy. It does crazy, useless shit. Commented Dec 3, 2013 at 2:47
  • so as of now the best solution is to iterate through the whole array to check each time? Commented Dec 3, 2013 at 2:52
  • numpy arrays with dtype=object are not very well developed. Basic things like indexing work. But binary operations are hit and miss. Commented Dec 3, 2013 at 4:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.