Operators & amp; quot; and & amp; difference analysis of amp; quot; is & amp; quot;
Preface
Before talking about the differences between the is and = operators, you must first know the three basic elements of an object in Python: id (id), python type () (data type) and value (value ). Is and = are used to compare and judge objects, but the content of comparison and judgment on objects is different. Next let's take a look at the specific differences.
In Python, there are two methods to compare whether two objects are equal. the differences are as follows:
Is to compare whether two references point to the same object (reference comparison ).
= Is to compare whether two objects are equal.
>>> A = [1, 2, 3] >>> B = a >>> B is a # a references to B, in the memory, they actually point to the use of an object "True"> B = a #, of course, their values are also equal "True" >>> B = a [:] # B obtains part a through Part a. Here, the slicing operation re-allocates the object, >>> B is a # so not to the same object is False> B = a # but their values are still equal to True
Implementation principle
Is compares whether the two are the same object, so it compares the memory address (id is the same ).
= Is a value comparison. Immutable objects, such as int and str, are compared directly. For objects known to Python, their _ eq _ functions are called for comparison. (In fact, known objects should also be compared through the built-in _ eq _ function ). If the _ eq _ function is implemented for a custom object, it is used for comparison. if it is not implemented, the effect is the same as =.
Object caching mechanism
Python caches small objects. The next time a small object is used, it searches in the cache area. if a small object is found, no new memory will be created, instead, the address of the small object is assigned to a new value. Example:
>>> c = 1>>> d = 1>>> print(c is d) True >>> 1000 is 10**3False>>> 1000 == 10**3True
The calculated value does not use the cache area. We can see from the first sample code.
For strings, you can use the intern function to forcibly use the cache zone.