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[1][1]='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[1][1] = 'AB'. Both sublists of old list and new list at index [1][1] were modified. This is because, both lists share the reference of same nested objects.
Also see Deep Copy
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 admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.