Ram Ram - 5 months ago 14
Python Question

Two variables in python have same id, but not lists or tuples - why?

Two variables in python have same id

a = 10
b = 10
a is b
>>> True


If I take two lists:

a = [1, 2, 3]
b = [1, 2, 3]
a is b
>>> False


according to this link Senderle answered that immutable object references have same id and mutable objects like lists have different id.

So now according to his answer, tuples should have same id - means

a = (1, 2, 3)
b = (1, 2, 3)
a is b
>>> False


ideally as tuples are not mutable it should return True, but it is returning
False
!

Can anyone help in explaining why?

Answer

Immutable objects doesn't have same id,and as a mater of fact this is not true for any type of objects that you define separately. Every time you define a object in python you create a new object with new id, but there are some exceptions for small integers (between -5 and 256) and small strings (interned strings, with a special length (usually less than 20 character)) which are single tones and have same id (actually one object with multiple pointer). You can check this fact with larger numbers:

>>> 300 is 3*100
False

Also note that is operator will check the object's identity not value. If you want to check the value you should use ==.

>>> 300 == 3*100
True

And since there is no such rule for tuples (other types) if you define 2 same tuple in any size they'll get their own ids:

>>> a = (1,)
>>> b = (1,)
>>> 
>>> a is b
False

And note that the fact of singleton integers and interned strings is true even when you define them within mutable and immutable objects:

>>> a = (100, 700, 400)
>>> 
>>> b = (100, 700, 400)
>>> 
>>> a[0] is b[0]
True
>>> a[1] is b[1]
False