Home > Software design >  Why is the id of the copied dictionary different from the one it was copied from?
Why is the id of the copied dictionary different from the one it was copied from?

Time:09-17

record={"Name":"Python","Age":"20"}
x=record.copy()
print(id(x)==id(record))

Why does it give False as an output when I run it?

CodePudding user response:

As per the definition of the inbuilt id() function https://docs.python.org/3/library/functions.html#id, it returns the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime.

The copy(), creates a new dictionary object from the existing dictionary.

The statement print(id(x)==id(record)) points that x and record have overlapping lifetime.

CodePudding user response:

Copies of mutable objects are distinct and autonomous instances that initially have the same content but can be changed individually. For comparison, a copy of an immutable object (e.g. a tuple) references the same memory space because its content will never change.

You can observe this phenomenon on immutable objects (e.g. tuples) with the same content that have the same id even though they are not even copies of each other:

>>> t = (1,2,3)
>>> id(t)
140707126155016
>>> u = (1,2,3)
>>> id(t)
140707126155016
>>>

For mutable objects (e.g. list, dict), the copy() method creates a new instance with a copy of the content.

>>> d = [1,2,3]
>>> c = d.copy()
>>> d,id(d)
([1, 2, 3], 140707126669064)
>>> c,id(c)
([1, 2, 3], 140707126356872)
>>> c[1] = 5                  # only affects the c instance (not d)
>>> d, id(d)
([1, 2, 3], 140707126669064)
>>> c, id(c)
([1, 5, 3], 140707126356872)

A simple variable assignment copies the reference to the same instance so both variable (original and assigned) reference the same content (which can be modified):

>>> d = [1, 2, 3]
>>> c = d
>>> d[1] = 5                 # same instance seen by both c and d
>>> c, id(c)
([1, 2, 3], 140707126135240)
>>> d, id(d)
([1, 2, 3], 140707126135240)
  • Related