I have seen it said that, in Python, comparisons with boolean values should be of the form if x:
, not if x == True:
, and certainly not of the form if x is True:
.
>>>
>>> id(True)
505509720
>>> a = True
>>> id(a)
505509720
>>> random_string_to_reference_a_different_area_of_memory = "Python"
>>> id(True)
505509720
>>>
Playing around with variables and looking at memory locations (see above), it looks to me like there is only one True
and one False
object, so why shouldn't we do if x is True:
(or is it actually fine to do so)?
Also, is there any reason why we shouldn't do if x == True
, other than the fact that the == True
is unnecessary; if so, would you be able to give me a description in terms of memory?
I personally feel that using is
is more appropriate than using ==
, since when we are doing a comparison it looks like we are actually looking at whether a variable points to the True
or False
object. Could anyone give me an explanation of what is best, and why, and how it all works?