How to deep copy a list? How to deep copy a list? python python

How to deep copy a list?


E0_copy is not a deep copy. You don't make a deep copy using list(). (Both list(...) and testList[:] are shallow copies.)

You use copy.deepcopy(...) for deep copying a list.

deepcopy(x, memo=None, _nil=[])    Deep copy operation on arbitrary Python objects.

See the following snippet -

>>> a = [[1, 2, 3], [4, 5, 6]]>>> b = list(a)>>> a[[1, 2, 3], [4, 5, 6]]>>> b[[1, 2, 3], [4, 5, 6]]>>> a[0][1] = 10>>> a[[1, 10, 3], [4, 5, 6]]>>> b   # b changes too -> Not a deepcopy.[[1, 10, 3], [4, 5, 6]]

Now see the deepcopy operation

>>> import copy>>> b = copy.deepcopy(a)>>> a[[1, 10, 3], [4, 5, 6]]>>> b[[1, 10, 3], [4, 5, 6]]>>> a[0][1] = 9>>> a[[1, 9, 3], [4, 5, 6]]>>> b    # b doesn't change -> Deep Copy[[1, 10, 3], [4, 5, 6]]


I believe a lot of programmers have run into one or two interview problems where they are asked to deep copy a linked list, however this problem is harder than it sounds!

in python, there is a module called "copy" with two useful functions

import copycopy.copy()copy.deepcopy()

copy() is a shallow copy function, if the given argument is a compound data structure, for instance a list, then python will create another object of the same type (in this case, a new list) but for everything inside old list, only their reference is copied

# think of it likenewList = [elem for elem in oldlist]

Intuitively, we could assume that deepcopy() would follow the same paradigm, and the only difference is that for each elem we will recursively call deepcopy, (just like the answer of mbcoder)

but this is wrong!

deepcopy() actually preserve the graphical structure of the original compound data:

a = [1,2]b = [a,a] # there's only 1 object ac = deepcopy(b)# check the resultc[0] is a # return False, a new object a' is createdc[0] is c[1] # return True, c is [a',a'] not [a',a'']

this is the tricky part, during the process of deepcopy() a hashtable(dictionary in python) is used to map: "old_object ref onto new_object ref", this prevent unnecessary duplicates and thus preserve the structure of the copied compound data

official doc


If the contents of the list are primitive data types, you can use a comprehension

new_list = [i for i in old_list]

You can nest it for multidimensional lists like:

new_grid = [[i for i in row] for row in grid]