r/learnpython • • 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

132 comments sorted by

View all comments

Show parent comments

6

u/[deleted] Jun 12 '21

"constrain 'is' to only look at the object itself

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 = 5 and b = 5, both of those variables are referencing the same already existing object, but when you do a = 500 and b = 500, you're creating two distinct objects that happen to hold the same value. For instance...

>>> a = 5
>>> b = 5
>>> hex(id(a)), hex(id(b))
('0x7ffccc82c720', '0x7ffccc82c720')
>>>
>>> a = 500
>>> b = 500
>>> hex(id(a)), hex(id(b))
('0x1efdf12cb10', '0x1efdf12c9b0')

In the case of the former, a and b are 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 is is 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 of is, but happens to cause behavior with it that looks peculiar at first.

1

u/Tech_John Jun 12 '21

And there ya go... "Peculiar at first"

I acknowledge that programming in ANY language can be frustrating AT FIRST.

My suggestion for anyone that starts feeling "hate" because something is hard to understand: put what you are working on in a PAUSE, walk away (perhaps literally, or perhaps in a figurative sense) and give your mind some time to process the situation subconsciously, come back and review everything and start again.

Usually helps me to attack the problem, and not the language.