is and == operators

is: identity operator

See the following example:

a=b=[1,2,3]
c=[1,2,3]
print(a==b)
print(a==c)
print(a is b)
print(a is c)
#输出
True
True
True
False

It can be seen that the is operator is used to determine identity, not equality, variables a and b are bound to the same list, and variable c is bound to another list with the same value and order, their values It may be equal, but it is not the same object. From the perspective of memory, the memory spaces they point to are different. a and b point to the same memory space, while c points to another memory space. It can be seen that the is operator is used to determine whether two objects are the same object, and == determines whether two objects are equal.

Look at this example again:

 

>>> a=b=5
>>> c=5
>>> a is b
True
>>> a is c
True

>>> x=y=500
>>> z=500
>>> x is y
True
>>> x is z
False

 

Obviously a and c are no longer in the same memory. Why does a is b return True? This is caused by Python's garbage collection mechanism. There is something called a small integer object pool inside python. In order to optimize the speed, Python will The small integers between [-5, 256] are stored in the small integer object pool in advance. When the numbers in this range are used in the program, they will point to the same piece of data in this object pool, and will not re-apply for a block. RAM. When the number of this interval is exceeded, a block of memory will be re-applied, so when it is 500, x is y returns False.

Note: This phenomenon is only valid when input in the command line. When running in pycharm or saving as a file for execution, it returns True. The specific reason is to be investigated.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324963486&siteId=291194637