Cloning in Python
1. Cloning in Python refers to creating an independent copy of an object.
2. Cloning does not create a new reference to the same object (aliasing).
3. This will ensure that changes made to the new copy will not affect the original.
4. Python provides different methods for shallow and deep cloning.
[Link] Copy (Shallow Cloning) [Link] List Slicing
Methods for creating a shallow copy include: This method creates a new list by slicing all
elements from the original.
[Link] the copy module's copy() function x= [1, 2, 3, 4, 5]
import copy y = x[ : ]
x = [[1, 2], [3, 4]] print(b)
y = [Link](x)
print(y) ----------------------------------------------------------
[Link] Copy
[Link] the [Link]() method: A deep copy creates a new object before
inserting copies of the items from
x = [1, 2, 3]
original list.
y = [Link]()
print(y)
[Link] [Link]() for Nested Lists
[Link] the list() constructor:
import copy
x = [1, 2, 3]
a = [[1, 2], [3, 4], [5, 6]]
y = list(x)
b = [Link](a)
print(y)
print(b)