Before talking about the difference between the two operatorsis and ==, you must first know what the objectcontains in Python The three basic elements are: id (identity identification), python type() (data type) and value (value). Both is and == are used to compare and judge objects, but the content of comparing objects is different. Let’s take a look at the specific differences.
There are two methods in Python to compare whether two objects are equal. Simply put, their differences are as follows:is compares two referencesWhether it points to the same object (reference comparison).
== is to compare whether two objects are equal.
>>> a = [1, 2, 3] >>> b = a >>> b is a # a的引用复制给b,他们在内存中其实是指向了用一个对象 True >>> b == a # 当然,他们的值也是相等的 True >>> b = a[:] # b通过a切片获得a的部分,这里的切片操作重新分配了对象, >>> b is a # 所以指向的不是同一个对象了 False >>> b == a # 但他们的值还是相等的 True
对象缓存机制
>>> c = 1 >>> d = 1 >>> print(c is d) True >>> 1000 is 10**3 False >>> 1000 == 10**3 True
strings, you can force the use of the buffer area by using the intern function.
The above is the detailed content of Analysis on the difference between operators '==' and 'is' in Python. For more information, please follow other related articles on the PHP Chinese website!