Python '!=' Is Not 'is not': Comparing Objects in Python (Summary)
In this course, you learned that
!= compare the value of two objects, whereas the Python
is not operators compare whether two variables refer to the same object in memory. If you keep this distinction in mind, then you should be able to prevent unexpected behavior in your code.
If you want to read more about the wonderful world of object interning and the Python
is operator, then check out Why you should almost never use “is” in Python. You could also have a look at how you can use
sys.intern() to optimize memory usage and comparison times for strings, although the chances are that Python already automatically handles this for you behind the scenes.
Now that you’ve learned what the equality and identity operators do under the hood, you can try writing your own
__eq__() class methods, which define how instances of this class are compared when using the
== operator. Go and apply your newfound knowledge of these Python comparison operators!
Congratulations, you made it to the end of the course! What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment in the discussion section and let us know.
Become a Member to join the conversation.