3

Similar to Two variables in Python have same id, but not lists or tuples But still not quite the same as it's not just for small values.

>> a = 1234; b = 1234; id(a); id(b); a is b
9447736
9447736
True
>>> a = 1234
>>> id(a)
9447616
>>> b = 1234
>>> id(b)
9447688
>>> a is b
False
>>> a = "abcd"; b = "abcd"; id(a); id(b); a is b
140282436530560
140282436530560
True
>>> a = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; b = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; id(a); id(b); a is b
140282436951600
140282436951600
True
>>> a = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; b = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; id(a); id(b); len(a); a is b
140282436951600
140282436951600
74
True
>>> a = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; b = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; id(a); id(b); len(a); a is b
140282436951600
140282436951600
74
True
>>> 
Khorkrak
  • 3,911
  • 2
  • 27
  • 37
  • 2
    "Small" ints and strs (like the ones in your example) are "interned". This means that there's a SINGLE copy of them somewhere in the memory space and that's the instance that every variable references – inspectorG4dget Aug 31 '17 at 15:52
  • 1
    @inspectorG4dget: It doesn't explain the difference between "a=1234;b=1234" and "a=1234\nb=1234", though – Eric Duminil Aug 31 '17 at 15:54
  • 3
    I think this is more of a case where the terminal/compiler exploits the spacial locality of immutable literals. Since 1084 is outside the range of interned integers anyway. – Moses Koledoye Aug 31 '17 at 15:56
  • The `False` case is only doable in the python CLI, if you write a test.py with the same stuff, it'll be `True` each time. So @MosesKoledoye seems right – pwnsauce Aug 31 '17 at 16:01
  • 1
    @MosesKoledoye nice catch! – Ma0 Aug 31 '17 at 16:01
  • @pwnsauce The behavior is an implementation detail. No guarantees for reproducibility across terminal (stdin) and/or files. – Moses Koledoye Aug 31 '17 at 16:02
  • off-topic but i like `id([]) == id([1,2,3,4])` >>> `True` – Chris_Rands Aug 31 '17 at 16:10

0 Answers0