2

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?

Vineeth Sai
  • 3,389
  • 7
  • 23
  • 34
Abd
  • 109
  • 1
  • 7

1 Answers1

2

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.

Vineeth Sai
  • 3,389
  • 7
  • 23
  • 34
  • I checked in jupyter notebook, the output is shown as in the question. – Abd Dec 17 '18 at 11:03
  • I checked in jupyter notebook, after repeating, id('a-b') statement, id is continuously changing. but in command prompt the value is always same. The output of above question i asked is complete opposite in command prompt. – Abd Dec 17 '18 at 11:10
  • @Abd Seems like the anaconda interpreter (the one that your jupyter is using) has different memory management system than the one in your computer. – Vineeth Sai Dec 17 '18 at 11:27
  • After checking a='a-b';b='a-b' statement, please check again with b='a-b' instead of b='new'. Here id(b) changes. Why? – Abd Dec 18 '18 at 07:10