Difference between "is" and "==" in Python
Definition and features of comparison operators
- operator “==” for value equality. It’s used to know if two objects have the same value.
- operator “is” for reference equality. It’s used to know if two references refer (or point) to the same object, i.e if they’re identical. Two objects are identical if they have the same memory address.
Two objects having equal values are not necessarily identical.
Python (CPython to be precise) caches short strings and small integers objects as singleton instances for performance reasons. Read more here - “What the f*ck Python!”.1
For integers from the range from -5 to 256 inclusive, the interpreter allocates space in memory in advance and gives the variables references to these objects, so such incidents are possible:
|
|
The is statement is syntactic sugar: a is b just wrapper for id(a) == id(b)
What does PEP8 say about this?
Comparisons to singletons like None should always be done with “is” or “is not”, never the equality operators ("==" and "!=").
Also, beware of writing if x when you really mean if x is not None — e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!2
“is” is faster than "==". After all, “is” is implemented in C, and is a simple comparison of the IDs of the two objects. No function call is needed, and we certainly don’t need to compare the values of the two objects, which can also take some time.3
Usecases for “is” and “==”
Use cases for is include:4
- None
- enum values (when using Enums from the enum module)
- usually modules
- usually class objects resulting from class definitions
- usually function objects resulting from function definitions
- anything else that should only exist once in memory (all singletons, generally)
- a specific object that you want by identity
Usual use cases for == include:
- numbers, including integers
- strings
- lists
- sets
- dictionaries
- custom mutable objects
- other builtin immutable objects, in most cases