Difference between is and == in Python

The difference between is and == in Python is as follows:

The environment is actually tested by IPython

In Python is is an object identity (object identity), == means equality;
is is judged by whether the memory addresses pointed to by the object are equal
== is judged by calling the method eq to determine whether the objects on both sides are equal
In general, if a is b returns True, it means that a, b point to the same memory address
a == b returns True, that is, the values ​​of a and b are equal

figure 1

Difference between is and == in Python

figure 2
Difference between is and == in Python

The comparison between Figure 1 and Figure 2 shows that the operation ideas are the same, but the returned results are different. Figure 1 is due to the role of the string residency mechanism in Python. In Python, for smaller strings, in order to To improve system performance, Python will retain a copy of its value. When creating a new and identical value, Python will directly point to the retained copy; the string given in Figure 2 belongs to a longer string, and Python does not It will reside, that is, no copy will be created, so different objects are created to save, although the value is the same, but the memory address is different.

Guess you like

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