Two variables in Python have same id, but not lists or tuples

Ram Vallury picture Ram Vallury · Jul 4, 2016 · Viewed 10.1k times · Source

Two variables in Python have the 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 the same id and mutable objects like lists have different ids.

So now according to his answer, tuples should have the same ids - meaning:

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!

What is the explanation?

Answer

Kasravnd picture Kasravnd · Jul 4, 2016

Immutable objects don't have the same id, and as a mater of fact this is not true for any type of objects that you define separately. Generally speaking, every time you define an object in Python, you'll create a new object with a new identity. However, for the sake of optimization (mostly) there are some exceptions for small integers (between -5 and 256) and interned strings, with a special length --usually less than 20 characters--* which are singletons and have the same id (actually one object with multiple pointers). You can check this like following:

>>> 30 is (20 + 10)
True
>>> 300 is (200 + 100)
False
>>> 'aa' * 2 is 'a' * 4
True
>>> 'aa' * 20 is 'a' * 40
False

And for a custom object:

>>> class A:
...    pass
... 
>>> A() is A() # Every time you create an instance you'll have a new instance with new identity
False

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

>>> 300 == 3*100
True

And since there is no such optimizational or interning rule for tuples or any mutable type for that matter, if you define two same tuples in any size they'll get their own identities, hence different objects:

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

It's also worth mentioning that rules of "singleton integers" and "interned strings" are true even when they've been defined within an iterator.

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

* A good and detailed article on this: http://guilload.com/python-string-interning/