0

lets look at below example.

>>> a=10
>>> b=10
>>> id(a)
41776876
>>> id(b)
41776876
>>> c=a
>>> id(c)
41776876
>>> d=10
>>> id(d)
41776876

Here for int, the same object is referring for all the variables where as for lists the object is getting changed.

>>> l1=[10]
>>> l2=[10]
>>> id(l1)
42220360
>>> id(l2)
52956416
>>> l3=l1
>>> id(l3)
42220360
>>> l4=[10]
>>> id(l4)
52981472

Kindly let me know how python is managing memory here??

Janaki
  • 31
  • 4
  • Possible duplicate of ["is" operator behaves unexpectedly with integers](http://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers) – DSM Mar 13 '17 at 08:41

1 Answers1

0

Integers are immutable. It doesn't matter if multiple integers share the same memory; nothing can possibly happen to the integer that would affect the shared references at all. As an optimization, Python maintains a cache of small integers, and reuses these when possible.

Lists, however, are mutable. If two different lists were stored in the same memory just because they had the same contents at the moment, this would be disastrous - any change to one list would be reflected in all of them, even though the connection between them is purely coincidental. Only if you explicitly make multiple references to the same list (as in your l3 = l1) are they actually shared in memory.

jasonharper
  • 9,450
  • 2
  • 18
  • 42