In Python, is and = are two methods for comparing two objects. pythonis
The is and = methods in Python to compare two objects
In Python, there are two ways to compare whether two objects are equal, namely, is and =, and the two are different.
- = Compare values (like the equals method in java)
- Is compares with references (it can be considered as a memory address, similar to = in java)
For:
>>> n = 1>>> n is 1True>>> b = '1'>>> b is 1False>>> n == bFalse
Because 1 and '1' are different in both the value and reference, the result is false.
For:
>>> n = 1>>> n is 1True
Here is a knowledge point. Simply put, for the primitive type of Integer type, reference comparison is a value comparison. However, Python adopts this method in integer implementation, for numbers between-5 and 256, keep the array in memory to store these numbers and reference them directly next time. The int object will be created for numbers out of this range.
The following code provides a simple example:
# The values of a and B exceed 256 >>>> a = 257 >>> B = 257 >>> the values of a is bFalse # a and B are between-5 and 256 >>> a = 256 >>>> B = 256 >>> a is bTrue
As shown in the preceding example ~ Python will not initialize a new memory space for the variable, but it will allocate a new space once it exceeds 256.
By printing the IDs of the two objects, you can directly see the differences between the memory addresses of the two objects, as shown below:
# The values of a and B exceed 256 >>>> a = 257 >>> B = 257 >>>>>>> id () 140638347685960 >>> id (B) 140638347686008 # The values of a and B are between-5 and 256 >>>> a = 256 >>> B = 256 >>> id () 140638347656864 >>> id (B) 140638347656864
The above is a detailed explanation of the comparison between Python is and =. If you have any questions, please leave a message or go to the community on this site for discussion. Thank you for reading this article and hope to help you. Thank you for your support for this site!