Search code examples
pythonswapidentify

Why does Python swaps variable ids when swaps variables


I thought every object take an id based on key.

>>> a = 10
>>> b = 20
>>> id(a)
1876869280
>>> id(b)
1876869440
>>> a,b=b,a
>>> id(a)
1876869440
>>> id(b)
1876869280

When swap the variables, their ids are swapped too. If every object has a unique id, then why ids are swapped? I thought id(a) and id(b) will be same after swap.


Solution

  • If every object has a unique id, then why ids are swapped?

    Because you swapped objects. The objects aren't a and b, they're 10 and 20. a and b are just names that the code uses to refer to those objects.