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:

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

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

Explanation: 

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