In short:
==
is for value equality and is
is for reference equality (same as id(a)==id(b)
). Python caches small objects(small ints, strs, etc) to save space (feature that has been since py2).
My original detailed answer with examples:
Because they are exactly the same!
is
will return True if two variables point to the same object, you can check the id
to see the truth!
Try this:
a = 'Test'
b = 'Test'
print(a is b)
print(id(a),id(b))
My output was:
True
140586094600464 140586094600464
So to save space Python will assign the pointer same location until a change is a made
Example:
a = 'Test'
b = 'Test'
print(a is b)
print(id(a),id(b))
a = 'Test'
b += 'Changed'
print(a is b)
print(id(a),id(b))
True
140586094600464 140586094600464
False
140586094600464 140585963428528
Once you make a change, strings being immutable will get new location in memory!
If this was something like list
, which is mutable even if they are same they will get separate location, so changes can be made!
#mutable
a= [1,2]
b= [1,2]
print(a is b)
print(id(a),id(b))
a[0] = -1
b[1] = -2
print(a is b)
print(id(a),id(b))
False
140586430241096 140585963716680
False
140586430241096 140585963716680
Int
eg:
a=100
b=100
print(a is b)
print(id(a),id(b))
True
10917664 10917664