0

I have read about how python creates objects and put "tags" for those as a variables assigned to that. However, I see that if there are two strings or integers with the same values, it allocates only one memory spot for it, unlike lists, tuples, dics. Is there a rule or list of types when one case happens but not the other? In particular, if I set

>>> x,y='a','a'
>>> x is y
True
>>> x,y=1,1
>>> x is y
True

But on the other hand, if I do

>>> x,y={'a':1},{'a':1}
>>> x is y
False
>>> x,y=(1,),(1,)
>>> x is y
False
>>> x,y=[1],[1]
>>> x is y
False
Medan
  • 101
  • 2
  • Two reasons: Python stores immutable literals in code constants and reuses those constants, *and* string literals that are also valid identifiers are interned (the same string object is reused over and over again rather than create a new instance). – Martijn Pieters Oct 28 '14 at 12:22

1 Answers1

0

Strings are immutable in Python and are reused. Dictionaries are not and hence can't be reused. New ones are created. It's just incidental that they have the same keys and values.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
  • This is what I thought initially, but how about tuples vs lists? First ones are immutable and lists are not, however, it still constructs two different objects in the memory for either ones. But it doesn't for strings and integers, i.e. simple types. – Medan Oct 28 '14 at 16:41
  • Good question. The difference is that CPython [interns strings](http://stackoverflow.com/questions/15541404/python-string-interning). Lists and tuples aren't interned and so aren't reused. – Noufal Ibrahim Oct 28 '14 at 17:42