Before you distinguish between the IS and = = operators, the first thing to know about the three basic features of objects in Python is the ID (identity), Python type () (data type), and value. IS and = = are the object of comparative judgment, but the object comparison of the content is not the same. Here's a look at the exact difference.
Python compares two objects for equality, a total of two methods, in short, they differ as follows:
IS is to compare whether two references point to the same object (reference comparison).
= = is the comparison of two objects equal.
| 1234567891011 |
>>> 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 |
Implementation principle
Is compares whether the two are the same object, so the memory address (ID is the same) is compared.
= = is a value comparison. Immutable objects, such as INT,STR, that directly compare values
Python is = =