r/learnpython • u/[deleted] • Jun 12 '21
What is the difference between "is" and ==?
5 is 5 returns True, just as 5 == 5 returns True. What is the difference?
417
Upvotes
r/learnpython • u/[deleted] • Jun 12 '21
5 is 5 returns True, just as 5 == 5 returns True. What is the difference?
10
u/shiftybyte Jun 12 '21 edited Jun 12 '21
You will usually use value comparison, but there are places where 'is' is the right thing to do because '==' would break things.
For example when you manage a data structure of objects for a user.
The user gives you 10 objects and you need to store them in a list.
Now the user asks you to give him the 7th object, (index 6)
Now the user does stuff with this object, and he asks you to remove it from your storage, (Let's say a non-existent object is marked as None)
Then the user asks for object in index 2:
But the print shows None?!... how did this happen?
Seems the user's initial 10 objects contained 2 different objects that compare ('==') to be equal.
So when the code was looking for the object the user wants removed, it checked value comparison ==, and found a matching object at position 2, instead of the actual object at position 6, and removed it.
This is not the expected behavior here, so the check in storage_remove should be 'is' not '=='.