Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.any() returns True but "is True" comparison fails [duplicate]

Tags:

python

numpy

If numpy.any() returns True the comparison with is True fails but with == True works. Does anyone know why?

A minimal example

from __future__ import print_function
import numpy

a = numpy.array([True])

if a.any() == True:
  print('== works')

if a.any() is True:
  print('is works')

The output of this code is just == works.

like image 227
floren Avatar asked Dec 11 '22 10:12

floren


1 Answers

numpy has it's own booleans, numpy.True_ and numpy.False_ that have different identities from Python's native booleans. Anyway, you should be using == for such equity comparisons

>>> a.any() is True
False
>>> a.any() is numpy.True_
True
>>> True is numpy.True_
False
>>> True == numpy.True_
True
like image 84
Chris_Rands Avatar answered Jan 12 '23 00:01

Chris_Rands