Make a copy of the list in Python

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

Recommended Posts

Make a copy of the list in Python
Display a list of alphabets in Python 3
Get the number of specific elements in a python list
Get the caller of a function in Python
Make a joyplot-like plot of R in python
Output in the form of a python array
Make a bookmarklet in Python
[Python] Copy of multidimensional list
Receive a list of the results of parallel processing in Python with starmap
Make a copy of a Google Drive file from Python
[python] Get the list of classes defined in the module
[Python] Outputs all combinations of elements in the list
Group by consecutive elements of a list in Python
A reminder about the implementation of recommendations in Python
How to pass the execution result of a shell command in a list in Python
[python] Manage functions in a list
python / Make a dict from a list.
[Python] Make the function a lambda function
About the basics list of Python basics
How to get a list of files in the same directory with python
Make sure all the elements in the list are the same in Python
[Python] How to make a list of character strings character by character
[Note] Import of a file in the parent directory in Python
How to get the last (last) value in a list in Python
How to get a list of built-in exceptions in python
Find the eigenvalues of a real symmetric matrix in Python
Get the value of a specific key in a list from the dictionary type in the list with Python
How to identify the element with the smallest number of characters in a Python list?
Copy of python
How to check in Python if one of the elements of a list is in another list
Check the behavior of destructor in Python
Write the test in a python docstring
OR the List in Python (zip function)
Make a relation diagram of Python module
Change the list in a for statement
Run the Python interpreter in a script
The result of installing python in Anaconda
[python] Get a list of instance variables
[python] [meta] Is the type of python a type?
The basics of running NoxPlayer in Python
Summary of built-in methods in Python list
In search of the fastest FizzBuzz in Python
Let's make a combination calculation in Python
The story of blackjack A processing (python)
Get the EDINET code list in Python
[Python] Get a list of folders only
How to determine the existence of a selenium element in Python
Try to get a list of breaking news threads in Python.
How to check the memory size of a variable in Python
Read the standard output of a subprocess line by line in Python
How to check the memory size of a dictionary in Python
A function that measures the processing time of a method in python
[python] Get the rank of the values in List in ascending / descending order
Get a list of files in a folder with python without a path
[Python] A program that rotates the contents of the list to the left
Get the number of readers of a treatise on Mendeley in Python
Get the value of a specific key up to the specified index in the dictionary list in Python
When I got a list of study sessions in Python, I found something I wanted to make
How to pass the execution result of a shell command in a list in Python (non-blocking version)
Sorted list in Python
Make a list of "Houbunsha 70th Anniversary Campaign" on Selenium in Amazon