Everything is an object in Python.

Objects in Python contain three basic elements: ID (identification), type(data type), and value(value). Objects can be compared for equality using == or is.

Both is and == are used to compare and judge objects, but the contents of comparison and judgment are different. Now what’s the difference?

Is compares whether the IDS of two objects are the same. That is, it compares whether two objects are the same instance object and refer to the same memory address.

== compares whether the contents of two objects are equal, and the object’s __eq__() method is called by default.


The following code was tested under Python3.5.

The == comparison operator differs from the IS identity operator

== is the comparison operator of Python’s standard operators, used to determine whether the values of two objects are equal.

Code 1:

>>> a = [1, 2, 3]
>>> b = a
>>> b is a 
True
>>> b == a
True
>>> b = a[:]
>>> b is a
False
>>> b == a
TrueCopy the code


Explain why? Is is also called the identity operator, which is whether the IDS are the same or not. A and B have different ids, so b==a is True, b is a is False

Code 2:

>>> id(a)
4364243328
>>> 
>>> id(b)
4364202696Copy the code

When are is and == identical?

Code 3:

>>> a = 256
>>> b = 256
>>> a is b
True
>>> a == b
True
>>>
>>> a = 1000
>>> b = 10**3
>>> a == b
True
>>> a is b
False
>>>Copy the code

Conclusion: Number types are not exactly the same.


Why is it the same at 256 but different at 1000?

For integer objects, Python caches some of the most frequently used integer objects and stores them in a linked list called Small_ints. Throughout Python’s life, wherever we need to refer to these integer objects, Instead of recreating new objects, they refer directly to objects in the cache. Python places these potentially frequently used integer objects in the range [-5, 256] in Small_ints, but whenever small integers are needed, they are taken from there instead of creating new objects temporarily.


Code 4:

>>> c = 'pythontab.com'
>>> d = 'pythontab.com'
>>> c is d
False
>>> c == d
True
>>> c = 'pythontabcom'
>>> d = 'pythontabcom'
>>> c is c
True
>>> c == d
TrueCopy the code


Conclusion: String types are not identical. This has to do with interpreter implementation.


Code 5:

> > > a = # (1, 2, 3) a and b for tuple type > > > b = (1, 2, 3) > > > a is b False > > > a = [1, 2, 3] # for list types a and b > > > b = [1, 2, 3] > > b > a is False > > > a = {' python: 100, "com" : 1} # a and b for dict > > > b = {' python: 100, "com" : 1} > > > a is b False > > > a = Set ([1, 2, 3]) for the set type a and b # > > > b = set ([1, 2, 3]) > > > a is b is FalseCopy the code

 

conclusion

When variables are numbers, strings, tuples, lists, dictionaries, is and == are not the same and cannot be used interchangeably! Use == when comparing values, and use is when comparing whether it is the same memory address. Of course, there is a lot of comparison in development.