1

X is given as below:

X = np.array([-1, 2, 0, -4, 5, 6, 0, 0, -9, 10])

My answer is: any(X==0).
But the standard answer is X.any(), and it returns True, which confuses me.

For me, X.any() is looking for if there is any True or 1 in the array. In this case, since there is no 1 in the given X array, it should have returned False. What did I get wrong? Thank you in advance!

6
  • 2
    "X.any() is looking for if there is any True or 1 in the array" - please RTM: numpy.org/doc/stable/reference/generated/numpy.any.html Commented May 23, 2022 at 11:57
  • Python and numpy see "truthy" values as true. "Truthy" means among other things all int values except 0. Commented May 23, 2022 at 11:59
  • What you want is (X==0).any() Commented May 23, 2022 at 12:00
  • @ForceBru I read this before, but I misunderstood what truthy value is. By the way, can you kindly explain what RTM is? I googled it but didn't find a likey definition. Thanks! Commented May 24, 2022 at 2:12
  • 1
    @ericzheng0404, RTM stands for "Read The Manual". Doing so often helps get the definitions straight: like what a "truthy" value is or what X.any actually does. Commented May 24, 2022 at 7:36

1 Answer 1

1

X.any() is an incorrect answer, it would fail on X = np.array([0]) for instance (incorrectly returning False).

A correct answer would be: ~X.all(). According to De Morgan's laws, ANY element is 0 is equivalent to NOT (ALL elements are (NOT 0)).

How does it work?

Numpy is doing a implicit conversion to boolean:

X = np.array([-1, 2, 0, -4, 5, 6, 0, 0, -9, 10])
# array([-1, 2, 0, -4, 5, 6, 0, 0, -9, 10])

# convert to boolean
# 0 is False, all other numbers are True
X.astype(bool)
# array([ True,  True, False,  True,  True,  True, False, False,  True, True])

# are all values truthy (not 0 in this case)?
X.astype(bool).all()
# False

# get the boolean NOT
~X.astype(bool).all()
# True
Sign up to request clarification or add additional context in comments.

2 Comments

I think your answer is a better one. By the way, does my answer any(X==0) make sense? I didn't see similar syntax used in manual examples, but it worked in this case. So, I'm wondering is it also a valid answer?
It works but this is pure python while (X==0).any() is vectorized. I would probably use (X==0).any() in a project as it is much more explicit than ~X.all()

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.