Object Cloning

Clone objects using the copy module (shallow and deep copy).

PythonIntermediate
Python
# Program to demonstrate object cloning

import copy

class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next


n1 = Node(1, Node(2))
shallow = copy.copy(n1)
deep = copy.deepcopy(n1)

print("Original next:", n1.next)
print("Shallow next:", shallow.next)
print("Deep next:", deep.next)

Output

Original next: <__main__.Node object at ...>
Shallow next: <__main__.Node object at ...>
Deep next: <__main__.Node object at ...>

copy.copy shares nested objects, while copy.deepcopy clones the entire object graph.