Is it preferred to do:
if x is y:
return True
or
if x == y
return True
Same thing for “is not”
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
x is yis different thanx == y.x is yis true if and only ifid(x) == id(y)— that is,xandyhave to be one and the same object (with the sameids).For all built-in Python objects (like strings, lists, dicts, functions, etc.), if
x is y, thenx == yis also True. However, this is not guaranteed in general. Strictly speaking,x == yis true if and only ifx.__eq__(y)returns True.It is possible to define an object
xwith a__eq__method which always returns False, for example, and this would causex == yto return False, even ifx is y.So the bottom line is,
x is yandx == yare completely different tests.Consider this for example:
PS. Instead of
it is more Pythonic to write
And similarly,
can be replaced with