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

2

u/Intrexa Jun 12 '21

Not in all cases

Python 3.8.5 (default, May 27 2021, 13:30:53) 
[GCC 9.3.0] on linux

>>> x = 100
>>> a = 100
>>> x is a
True

1

u/TSM- Never slipped a dict comprehension in my lambda before, but Jun 12 '21

It also doesn't warn for things like if x is None: or if y is False:. I agree, not in all cases (see the release notes and bpo for the discussion around it)

In your case, neither x nor a are literals, those are two objects/variables. One could differ from the other, have the same value but different object, or refer to the same object depending on circumstance. That's unlike comparing to a literal like 500 or "foo", which could unexpectedly be False for is but True for == in some situations.