0

I think it is unnecessary, but want to find a answer. It is a bit hard to explain. I hope my words are clear enough. I want to create a function to judge if we can find a value from an array. If we can find the value in where statement, output "find the value". If the value cannot be found in the array, output "cannot find the value".

I try two ways, but cannot figure out how to equal to an empty result for np.where.

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 4, 4])
x = np.where(arr == 8)
# first method
if x:
    print("find the value")
else:
    print("cannot find the value")
# second method
if x is not None:
    print("find the value")
else:
    print("cannot find the value")

Certainly, I can use

if x in arr

But I think it can be a question about python knowledge and skills. If I cannot find any thing in a where statement. What is the return value? It still returns something, not a None. So what is it? How can I create a value to equal to it.

  • 1
    "in" is more readable, and efficient ; https://stackoverflow.com/a/7088674/7212665 – Demi-Lune Dec 20 '21 at 12:47
  • 2
    Be careful that np.where does not return an array, but a tuple (of size 1 in this case). Its boolean value will always be True, whether the number was found or not. Always "print(x)" when you are in doubt... – Demi-Lune Dec 20 '21 at 12:50
  • @Demi-Lune Thanks. But I tried print(x == () ) . It shows False. So it does not look like a normal empty tuple. – Lawrance Zhang Dec 20 '21 at 13:06

0 Answers0