0

Bool value of np.NaN is True. Then why and/or operation behaves so random in python.

bool(np.nan) == True

If True or np.nan evaluates to True then why does np.nan or True evaluate to nan? And this is completely reverse for and operation:

True and np.nan is nan while np.nan and True is True.

ayhan
  • 70,170
  • 20
  • 182
  • 203
dgomzi
  • 106
  • 1
  • 14
  • I have trouble understanding your examples and the question itself. Anyway due to operator precedence `x and y == z` is equivalent to `x and (y == z)`. Thus obviously is not the same as `y and x == z`. – freakish Jun 05 '18 at 13:21
  • 1
    See this SO Post... https://stackoverflow.com/q/43925797/6361531 – Scott Boston Jun 05 '18 at 13:22
  • 2
    In addition to Jacques' explanation, this is called [short circuiting](https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not). Try `2 or 1/0` for example, this will return `2` because the first operand is Trueish and its value is 2. But if you change the order it will raise a ZeroDivisionError. – ayhan Jun 05 '18 at 13:29

1 Answers1

1

This is due to the way the interpreter evaluates expressions with and/or:

  • or expressions:

    If the first operand is True or equivalent to True, the second operand is not evaluated and the value of the first operand is returned.

    If the first operand is False or equivalent to False, the second operand is evaluated and returned

    Examples:

    True or np.nan: bool(True) is True, therefore return True

    np.nan or True: bool(np.nan) is True, therefore return np.nan

    False or np.nan: bool(False) is False, therefore return np.nan

  • and expressions:

    If the first operand is False or equivalent to False, the second operand is not evaluated and the value of the first operand is returned

    If the first operand is True or equivalent to True, the second operand is evaluated and returned

    Examples:

    True and np.nan: bool(True) is True, therefore return np.nan

    np.nan and True: bool(np.nan) is True, therefore return True

    False and np.nan: bool(False) is False, therefore return False

Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75