1

How the memory allocation happens in Python?

>>> a=1
>>> b=1
>>> id(a)
2011353552
>>> id(b)
2011353552
>>> b+=1
>>> id(b)

Here, id(a) is equal to id(b). When I increment the value of b id(b) changes. Would anyone please shed some light on this?

viraptor
  • 33,322
  • 10
  • 107
  • 191

2 Answers2

2

There's a few misconceptions in the question, so I'll just give you some facts and hope it helps:

  1. Since number objects are immutable, they may point to the same memory. Specifically a 1 that comes from the source can (but doesn't have to) be always the same object.

  2. You don't really increment the value of b to be technically correct. You create a new object representing 2 (or get the existing one) and assign it to the b variable. It's a new object now.

  3. id() is for a unique identifier of objects. It doesn't have to relate to memory allocation at all. Currently it does, because cPython uses it this way. But as the documentation states:

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.

That's all - nothing more, nothing less. There are multiple optimisations that come into play here, so I wouldn't expect the id() to have any kind of reasonable behaviour.

viraptor
  • 33,322
  • 10
  • 107
  • 191
0

This is because in python everything is an object and small integer are singleton from -5 to 256 and are cached that is why id(a) == id(b) Now when you do b += 1 you reassign b to b + 1 which is not incrementation. As you can see a and b point to the same object in your first case but then you reassign b it points to different object.

>>> a = 1
>>> b = 1
>>> a is b
True
>>> b += 1
>>> a is b
False
styvane
  • 59,869
  • 19
  • 150
  • 156