[Python] The difference between is and ==

== is a comparison operator used to compare whether two values ​​are equal, and the result returns Boolean type True or False

The is operator is to compare whether the memory address where the value is located is the same, and the result returns a Boolean type True or False

aList = ['a','b','c']
bList = ['a','b','c']
# True
print(aList == bList)
# False
print(aList is bList)

# 1282636127624
print(id(aList))
# 1282636127368
print(id(bList))

Since the memory addresses of aList and bList are different, even if the values ​​are the same, the result still returns False

The same situation as above will also occur in the dictionary dict and the tuple Tuple, and the result returned by the is operator is also False 

aDict = {'a':1,'b':2}
bDict = {'a':1,'b':2}
# True
print(aDict == bDict)
# False
print(aDict is bDict)

# 1282572984184
print(id(aDict))
# 1282573081192
print(id(bDict))
aTuple = ('a','b','c','d')
bTuple = ('a','b','c','d')
# True
print(aTuple == bTuple)
# False
print(aTuple is bTuple)

# 1282636178280
print(id(aTuple))
# 1282636178920
print(id(bTuple))

When using the == comparison operator and the is operator for numeric types, strings, and bools, the returned results are True

a = 12
b = 12
# True
print(a == b)
# True
print(a is b)

# 1455517088
print(id(a))
# 1455517088
print(id(b))
aStr = 'Andy'
bStr = 'Andy'
# True
print(aStr == bStr)
# True
print(aStr is bStr)

# 1282635725992
print(id(aStr))
# 1282635725992
print(id(bStr))
aBool = True
bBool = True
# True
print(aBool == bBool)
# True
print(aBool is bBool)

# 1455026336
print(id(aBool))
# 1455026336
print(id(bBool))

The == and is operators return results depending on the data type they are passed in 

Question: a is b is True, must a == b be True?

a = ['a','b','c']
b = a
# True
print(a is b)
# True
print(a == b)
a = float('nan')
b = a
# True
print(a is b)
# False
print(a == b)

A == comparison between nan and any value (including comparison with itself) returns False 

Guess you like

Origin blog.csdn.net/Hudas/article/details/130461297