7-3. Copy

Object ID

  • The id() function returns a unique id for the specified object
  • All objects in Python has its own unique id
  • The id is assigned to the object when it is created
  • The id is the object's memory address and will be different for each time you run the program
  • Except for some object that has a constant unique id, like integers from -5 to 256, frequently used, saving memory and improving performance

 

Copy List

Example:

 

Output:

num1: [1, 2, 3, 4]

num1: [1, 2, 3, 4]
num2: [1, 2, 3, 4]

After changing a value:
num1: [1, 99, 3, 4]
num2: [1, 99, 3, 4]

 

Explanation: 

  • num2 = num1 does not make a new copy of the list.
  • Any change to the list via num1 or num2 will reflect in both because they share the same list object.

 

Example: Shallow Copy

 

Output:

num1: [[1, 2], [3, 4]]
num2: [[1, 2], [3, 4]]

num1's id 1700470845184
num2's id 1700470445888

After changing a value:
num1: [[10, 2], [3, 4]]
num2: [[10, 2], [3, 4]]

num1[0]'s id 1700468385088
num2[0]'s id 1700468385088

num1[1]'s id 1700468533504
num2[1]'s id 1700468533504

Explanation: 

  • copy() or slicing ([:]) makes a shallow copy: only the outer list is copied.
  • Inner elements (like nested lists) are still shared.

 

Example: Deep Copy

Output:

num1: [[1, 2], [3, 4]]
num2: [[1, 2], [3, 4]]

num1's id 2163258035520
num2's id 2163257900608

After changing a value:
num1: [[1, 2], [3, 4]]
num2: [[10, 2], [3, 4]]

num1[0]'s id 2163255781632
num2[0]'s id 2163257900480

num1[1]'s id 2163255633216
num2[1]'s id 2163257900544

 

Explanation: 

  • num2 is a completely separate object.
  • All inner lists are also copied — no shared references remain between num1 and num2.