Home  >  Article  >  Backend Development  >  Detailed explanation of operators "==" and "is" in Python

Detailed explanation of operators "==" and "is" in Python

WBOY
WBOYOriginal
2016-12-05 13:27:201122browse

Foreword

Before talking about the difference between the two operators is and ==, you must first know the three basic elements contained in objects in Python, namely: id (identity), python type() (data type) and value (value) . Both is and == are used to compare and judge objects, but the contents of object comparison and judgment are different. Let’s take a look at the specific differences.

There are two methods to compare whether two objects are equal in Python. In simple terms, their 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的引用复制给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 what is compared is the memory address (whether the id is the same).

== is a value comparison. Immutable objects, such as int, str, will directly compare values. For objects known to Python, their __eq__ function is called for comparison. (In fact, known objects should also be compared through the built-in __eq__ function). For custom objects, if the __eq__ function is implemented, it will be compared. If it is not implemented, the effect is the same as ==.

Object caching mechanism

Python will cache relatively small objects. The next time a relatively small object is used, it will search in the cache area. If it is found, it will not open up new memory, but continue to assign the address of the small object to a new value. . Example:

>>> c = 1
>>> d = 1
>>> print(c is d) 
True
 
>>> 1000 is 10**3
False
>>> 1000 == 10**3
True

The calculated assignment does not use the buffer area. This can be seen from the first code example.

For strings, you can force the use of the buffer by using the intern function.

Summary

The above is the entire content of this article. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, you can leave a message to communicate.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn