Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Id's of immutable types

Tags:

python

I'm a little confused about the distinction between mutable and immutable objects. I tried the following chunk of code to find the id's of objects:

tuple1 = ('Object1', 'Object2')
print id(tuple1)
tuple2 = ('Object1', 'Object2')
print id(tuple2)
list1 = ['Object1', 'Object2']
print id(list1)
list2 = ['Object1', 'Object2']
print id(list2)
string1 = "Foo bar"
print id(string1)
string2 = "Foo bar"
print id(string2)

I got the same id for the strings, and different id's for the lists, but a different id for the tuples. Shouldn't they have the same id? I was wondering if someone could explain how that works?

Thanks

like image 958
iman453 Avatar asked Dec 18 '25 05:12

iman453


2 Answers

Same IDs means the exact same object, but an implementation of Python is free to optimize the creation of immutable objects as it pleases. For example, in CPython 2.6.6 small integer objects are cached, so:

>>> x=256
>>> x is 256
True
>>> x=1024
>>> x is 1024
False

[NOTE: 'is' tests for object identity (same ID)]

There are no guarantees this result will be the same in other implementations. An implementation could cache immutable tuples, but which tuples are common? If as you suggest all identical tuples return the same id, then all tuples created by a program would have to be cached, and each new creation of a tuple would have to search the cache to see if it had been created before, which would be time consuming.

Use == to test for object equality, regardless of ID.

like image 84
Mark Tolonen Avatar answered Dec 20 '25 20:12

Mark Tolonen


You get the same id with the strings because string literals can be interned. You don't get the same id for the tuples because tuples are not interned.

A data structure that is mutable can not reasonably be interned (read: doing so would cause very confusing behaviour), so if strings were mutable, they could not be interned. However this does not mean that all immutable data structures are interned.

like image 32
sepp2k Avatar answered Dec 20 '25 20:12

sepp2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!