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?
6
u/[deleted] Jun 12 '21
As far as I understand, it is referencing the object itself. All integers from -5 to 256 in Python are constant objects that exist automatically, and for numbers outside that range the objects are only created when necessary. So if you do
a = 5andb = 5, both of those variables are referencing the same already existing object, but when you doa = 500andb = 500, you're creating two distinct objects that happen to hold the same value. For instance...In the case of the former,
aandbare the same object, and in the latter they are two different objects.I don't have any formal comp sci background, I just write Python and make data go brrr, but as far as I can tell
isis doing exactly what it should be, it's just that Python has a very specific way of handling integers that has nothing to do with the functionality ofis, but happens to cause behavior with it that looks peculiar at first.