TLDR: is-comparison works with Python bool
's and doesn't work with numpy bool_
's. Are any another differences exist?
I ran into a strange behaviour of booleans couple of days ago. When I tried to use is-comparison for this numpy array:
arr1 = np.array([1,0,2,0], dtype=bool)
arr1
Out[...]: array([ True, False, True, False])
(These variable names are based on fiction and any similarity to real variable names or production code are purely coincidental)
I saw this result:
arr1 is True
Out[...]: False
It was logical because arr1
is not True or False, it is numpy array. I checked this:
arr1 == True
Out[...]: array([ True, False, True, False])
This worked as expected. I mentioned this cute behaviour and forgot it immediately. Next day I checked True-ness of the array elements:
[elem is False for elem in arr1]
and it returns me this!
Out[...]: [False, False, False, False]
I was really confused because I remembered that in Python arrays (I thought that the problem is in arrays behaviour):
arr2 = [True, False, True, False]
[elem is False for elem in arr2]
it works:
Out[...]: [False, True, False, True]
Moreover, it was working in my another numpy array:
very_cunning_arr = np.array([1, False, 2, False, []])
[elem is False for elem in very_cunning_arr]
Out[...]: [False, True, False, True, False]
When I dived into my array, I unraveled that very_cunning_arr
was constructed by numpy.object
because of couple of non-numeric elements so it contained Python bools and arr1
was constructed by numpy.bool_
. So I checked their behaviour:
numpy_waka = np.bool_(True)
numpy_waka
Out[...]: True
python_waka = True
python_waka
Out[...]: True
[numpy_waka is True, python_waka is True]
And I finally found the difference:
Out[...]: [False, True]
After all of these I have two questions:
- Do
numpy.bool_
andbool
have some another differences in their common behaviour? (I know thatnumpy.bool_
has many numpy functions and parameters, like.T
and others) - How one can check if the numpy array contains only numpy booleans, without Pythonic bools?
(PS: Yes, NOW I know that comparing to True/False with is
is bad):
Don't compare boolean values to True or False using ==.
Yes: if greeting: No: if greeting == True: Worse: if greeting is True:
Edit 1: As mentioned in another question, numpy has its own bool_
type. But the details of this question are bit different: I found that is-statements works differently, but prior to this difference - is there something else is different in common bool_
and bool
behaviour? If yes, what exactly?