5

Two individually created mutable list have different ids.

Python SHELL: (mutable)

>>> mylist = ['spam', 'eggs']
>>> yourlist = ['spam', 'eggs']
>>> id(mylist), id(yourlist)
(49624456, 48910408)

While two individually created immutable strings have similar ids.

Python SHELL: (immutable)

>>> a = 10
>>> b = 10
>>> id(a), id(b)
(507099072, 507099072)

Is a and b referencing to a same object? If no, why ids are similar? Is mylist and yourlist referencing to different objects? If yes, why they have different ids.

1
  • mutable objects can mutate for that reason, list are created twice but if you check the id of element 0 of both list they should be identical. Since lists are mutable, you cannot expect list to point to the same object even if every "cell" inside the list point to the same "immutable" objects. Immutable objects can't mutate for that reason, python can optimize it and prevent duplicate. Commented Jan 13, 2014 at 12:46

1 Answer 1

6

Python caches some small strings and numbers: http://docs.python.org/2/c-api/int.html#PyInt_FromLong

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.

And id(some_list) always gives you the address of container - list object in memory, not strings in list!

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to create two variables with the same value between -5 and 256 but have them as different objects? a = 2, b = 2, and then a is b will return True. Is there a way to have both with a value of 2 but be different objects?
@JesseZhuang i see only one way - by int subclassing. All instances of your own integer class will be different objects...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.