-3

I have a python array that may or may not be None:

    arr = None # or possibly an array

    x = arr == None

    if x: 
      # do something

And it works for cases in which arr = None, but if it is an array, I calculate the indices of the array which equal None, instead.

What is the expression which will evaluate to true if some entity in python is, as a whole, == None?

Chris
  • 28,822
  • 27
  • 83
  • 158
  • 1
    What does calculate_array_obj do? Checking for None is done as `if x is None` – Norrius May 31 '18 at 14:47
  • @Norrius and that is the answer to my question, so why is providing out-of-scope information important? – Chris May 31 '18 at 14:48
  • So was your actual question “how to compare to None in Python”? Sorry, it wasn't obvious straight away. I figure it is indeed irrelevant then. – Norrius May 31 '18 at 14:49
  • Well, that's why we need the context: to figure out what you really needed! – Norrius May 31 '18 at 14:51
  • @Norrius guess you answered on your first comment, so I don't understand what you mean – Chris May 31 '18 at 14:51
  • 2
    @bordeo to be fair, I don't see Norrius's comments as being hostile or anti-stack overflow rant, your question wasn't very clear, and they were asking for clarification. In no way did they put you or your question down.. It seems like you are the one being hostile right now... – MooingRawr May 31 '18 at 14:53
  • If you want to make your questions more clear, take a look at how you can make a [mcve], as well as check out the [help] to improve in the future! – user3483203 May 31 '18 at 14:53
  • 4
    Possible duplicate of [not None test in Python](https://stackoverflow.com/questions/3965104/not-none-test-in-python) – quamrana May 31 '18 at 14:54
  • @MooingRawr I see it as the beginnings of one, followed by the Minimal, Complete and Verifiable thump. Which just happened. And yet I already have a great, high quality answer below! – Chris May 31 '18 at 14:54

2 Answers2

2

this should be sufficient

if x is None
Chris
  • 28,822
  • 27
  • 83
  • 158
vk-code
  • 950
  • 12
  • 22
0

If I understand corretly, your array is a numpy array, or any other data type that implements __eq__ to return something other than a single bool.

In [1]: array = None

In [2]: array == None
Out[2]: True

In [3]: array = np.array([1, 2, 3, 4, 5])

In [4]: array == None
Out[4]: array([False, False, False, False, False], dtype=bool)

In this case, you can still use is None, which is the preferred way to check whether something is None anyway:

In [5]: array is None
Out[5]: False

Some other options would be to not initialize the array as None in init and use hasattr to check whether the array has already been properly defined, or just try to access the array and create it in case of an exception. However, using is None or is not None is probably the best way.

tobias_k
  • 81,265
  • 12
  • 120
  • 179