Example1:
>>>a,b='a-b','a-b'
>>>a is b
True
Example2:
>>>a='a-b';b='a-b'
>>>a is b
False
Here Example1 and Example2 show different results. Can anybody explain to me why it is happening like this?
Example1:
>>>a,b='a-b','a-b'
>>>a is b
True
Example2:
>>>a='a-b';b='a-b'
>>>a is b
False
Here Example1 and Example2 show different results. Can anybody explain to me why it is happening like this?
is
operator checks for the identity of the variable. i.e the id(var)
. And is
operator doesn't check for equality it checks for identity. So in your case both are variables are pointing to the same memory location. You can see that by using id
.
>>> a='a-b';b='a-b'
>>> a is b
True
>>> id(a)
2885821331920
>>> id(b)
2885821331920
So Python is just using the same memory location for both the immutable
variables instead of creating a new one to reduce memory waste.
And for your case, in the first example it assigned the same identity and for the second Example it didn't assign the same identity.
And once you change the variable's value it's memory location is changed and this happens..
>>> b = 'new' # Changing value
>>> id(a)
2885821331920
>>> id(b)
2885782761064
>>> a is b
False
If you properly want to test for equality you might be better off with ==
operator.