The difference between is and == from the three elements of Python objects
Three elements of Python object
Python objects contain three basic elements id, type and value:
element | illustrate | method of obtaining |
---|---|---|
id | Identity, basically a memory address | id(obj) |
type | type of data | type(obj) |
value | value |
The difference between is and ==
logo | name | Judgment factor |
---|---|---|
is | identity operator | id |
== | comparison operator | value |
Example
Example 1
a = {"a":1, "b":2}
b = a.copy()
a == b # True value一样
a is b # False id不一样
- 1
- 2
- 3
- 4
- 5
Example 2
>>> x = y = [4,5,6]
>>> z = [4,5,6]
>>> x == y
True
>>> x == z
True
>>> x is y
True
>>> x is z
False
>>>
>>> print id(x)
>>> print id(y)
>>> print id(z)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
Example 3
>>> a = 1 #a和b为数值类型
>>> b = 1
>>> a is b
True
>>> id(a)
>>> id(b)
>>> a = 'cheesezh' #a和b为字符串类型
>>> b = 'cheesezh'
>>> a is b
True
>>> id(a)
>>> id(b)
>>> a = (1,2,3) #a和b为元组类型
>>> b = (1,2,3)
>>> a is b
False
>>> id(a)
>>> id(b)
>>> a = [1,2,3] #a和b为list类型
>>> b = [1,2,3]
>>> a is b
False
>>> id(a)
>>> id(b)
>>> a = {'cheese':1,'zh':2} #a和b为dict类型
>>> b = {'cheese':1,'zh':2}
>>> a is b
False
>>> id(a)
>>> id(b)
>>> a = set([1,2,3])#a和b为set类型
>>> b = set([1,2,3])
>>> a is b
False
>>> id(a)
>>> id(b)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
It can be seen from Example 3 that a is b is True only in the case of numeric and string types, and a is b is False when a and b are tuple, list, dict or set types.