Struggling to understand a specific behaviour of the is-operator

Viewed 111

Can someone explain me this behaviour?

a = 'Test'
b = 'Test'
print(a is b)  # True

I have expected the result to be False, because a and b are different references. The shown result I would have expect when using the equal-operator (==) for comparing on value-equality.

The is-operator is for to compare reference-equality? Or have I get that wrong?

What's the reason for the shown behaviour?

1 Answers

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
Related