Introduction

The result of execution with Python 3.8.3.

Copy of list

Sometimes I want to make a copy of the list, change the values and compare it to the original. In that case, you need to write using the deepcopy method of the copy module as follows.

1D list

When the list is one-dimensional, you can copy it with `deepcopy ()`, slice, `list ()`, etc.

`list_copy_example_1.py`

``````
import copy
list_1 = [0,1,2]
list_2 = copy.deepcopy(list_1) #deepcopy()use
list_3 = list_1[:] #Slice the original list
list_4 = list(list_1) #list()use

list_2[0] = 1000
list_3[0] = 2000
list_4[0] = 3000
print(list_1)
print(list_2)
print(list_3)
print(list_4)
``````

The output looks like this.

``````[0, 1, 2]
[1000, 1, 2]
[2000, 1, 2]
[3000, 1, 2]
``````

2D list

If the list is two-dimensional (or higher), you can copy it with `deepcopy ()`. Slices and `list ()` don't work (see below).

`list_copy_example_2.py`

``````
import copy
list_1 = [[0,1,2], [3,4,5]]
list_2 = copy.deepcopy(list_1)

list_2[0][0] = 1000
print(list_1)
print(list_2)
``````

The output looks like this.

``````[[0, 1, 2], [3, 4, 5]]
[[1000, 1, 2], [3, 4, 5]]
``````

Patterns that don't work

Substitute with =

Since you are copying the list reference itself, the values in the original list will also change.

`anti_pattern_1.py`

``````
#=Substitute with
list_1 = [0,1,2,3]
list_2 = list_1

list_2[0] = 1000
print(list_1)
print(list_2)
``````

output

``````[1000, 1, 2, 3]
[1000, 1, 2, 3]
``````

Slice, copy with list ()

The story of making a non-pass-by-reference copy of a Python list states that copying in slices is easy, but this is ** a list Only works in 1D **.

When the list is more than two dimensions, it looks like this: It doesn't seem to work because passing by reference occurs on the way.

`anti_pattern_2`

``````
#Copy the original list in slices(2D)
list_3 = [[0,1,2], [3,4,5]]
list_4 = list_3[:]

list_4[0][0] = 1000
print(list_3)
print(list_4)
``````

output

``````[[1000, 1, 2], [3, 4, 5]]
[[1000, 1, 2], [3, 4, 5]]
``````

You can also get the same result by using the `list ()` method instead of slicing.

Commentary

When you duplicate a list normally, the reference itself is copied, not the value. This is called a ** shallow copy **. Conversely, copying only the value is called ** deep copy **. In Python, a shallow copy is applied to complex objects such as lists and dictionaries unless otherwise specified. The reason why the multidimensional list was passed by reference when copied in slices is probably because the second dimension copy inside the slice was a shallow copy. And the `copy.deepcopy ()` method is an instruction to "make a deep copy". With it, even a copy of a multidimensional list will make a deep copy of every element. See the official copy --- shallow copy and deep copy operations for more information.

Summary

Slice for 1D list, `list ()`, `copy.deepcopy ()` `Copy.deepcopy ()` for multidimensional lists