Try it here
Subscribe
copy() function

Python shallow copy

python_shallow_copy

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.

Syntax :

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.

Example:

>>> 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

Writer profile pic

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 admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.



Post Comment

Comments( 0)

×

Forgot Password

Please enter your email address below and we will send you information to change your password.