The copy() method returns a shallow copy of the list.
A list can be copied with = operator
The problem with copying the list in this way is that if you modify the new list, the old list is also modified.
>>> old = [1,2,3] >>> new = old >>> new [1, 2, 3] >>> new.append(4) >>> new [1, 2, 3, 4] >>> old [1, 2, 3, 4] >>>
if you need the original list unchanged when the new list is modified, you can use copy() method. This is called shallow copy.
In shallow copy, 2 or more objects having same value points to different memory location.
new_list = list.copy()
The copy() function returns a list. It doesn't modify the original list.
>>> old [1, 2, 3, 4] >>> new=old.copy() >>> new [1, 2, 3, 4] >>> new.append(10) >>> new [1, 2, 3, 4, 10] >>> old [1, 2, 3, 4] >>>
However a shallow copy doesn't create a copy of nested objects, instead it just copies the reference of nested objects. This means, a copy process does not recurse or create copies of nested objects itself.
>>> old=[[1,2],[2,3],[3,4]] >>> new = old.copy() >>> new [[1, 2], [2, 3], [3, 4]] >>> old [[1, 2], [2, 3], [3, 4]] >>>
The new list contains references to original nested objects stored in old list.
However, when you change any nested objects in old_list, the changes appear in new list.
>>> old='AB' >>> old [[1, 2], [2, 'AB'], [3, 4]] >>> new [[1, 2], [2, 'AB'], [3, 4]] >>>
In the above program, we made changes to old list i.e old_list = 'AB'. Both sublists of old list and new list at index  were modified. This is because, both lists share the reference of same nested objects.
Also see Deep Copy
Anmol on Jul 15, 2020 at 01:04 am
This article is contributed by Anmol. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to email@example.com . See your article appearing on the dEexams.com main page and help others to learn.