[Python] Solution to the problem that elements are linked when copying a list

Introduction

Python: 3.7.4

Copy list a to list b, just as you would copy a value Suppose you change only the middle element of list b.

copy_test.py


a = [1, 2, 3, 4, 5]
b = a
b[2] =5
print(a)
print(b)

Execution result (failure example)

For some reason, the element in the middle of list a also changes.

output


[1, 2, 5, 4, 5]
[1, 2, 5, 4, 5]

Solution 1: Use the copy module

With the copy module, list a and list b are no longer linked.

copy_test2.py


import copy

a = [1, 2, 3, 4, 5]
b = copy.deepcopy(a)
b[2] =5
print(a)
print(b)

Solution 2: Use slices

If you write a [:], everything in the element will be passed to list b.

copy_test3.py


a = [1, 2, 3, 4, 5]
b = a[:]
b[2] =5
print(a)
print(b)

<2019/12/22: From shiracamus> copy.deepcopy makes a complete copy, but copy.copy and slice copies are shallow copies. The effect remains in the case of multiple lists. → Solution 2 does not seem to work in the case of multiple lists.

copy_test4.py


a = [[1], [2], [3], [4], [5]]
b = a[:]
b[2][0] = 5
print(a)
print(b)

As you pointed out, multiple lists will link the results.

output


[[1], [2], [5], [4], [5]]
[[1], [2], [5], [4], [5]]

Execution result (success example)

As expected, only the middle element of list b has changed. Solution 2 seems to be safer to use because it has the problem that it cannot be used with multiple lists.

output


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

Recommended Posts

[Python] Solution to the problem that elements are linked when copying a list
A solution to the problem that the Python version in Conda cannot be changed
A solution to the problem that files containing [and] are not listed in glob.glob ()
[Python] A program that rotates the contents of the list to the left
Python list comprehensions that are easy to forget
A python amateur tries to summarize the list ②
Solution to the problem that build does not end when installing OpenCV (PEP517)
Things to note when initializing a list in Python
How to sublist a list including the elements that are left over after dividing it into specific lengths
A story that got stuck when trying to upgrade the Python version on GCE
How to check in Python if one of the elements of a list is in another list
How to find the first element that matches your criteria in a Python list
A solution to the problem that kernel restarting frequently occurs when running PyQt system with jupyter or Spyder IDE
Make sure all the elements in the list are the same in Python
Get the number of specific elements in a python list
Points to note when deleting multiple elements from the List
How to get the last (last) value in a list in Python
[Python3] List of sites that I referred to when I started Python
Finding a solution to the N-Queen problem with a genetic algorithm (1)
Extract the value closest to a value from a Python list element
ABC's A problem analysis for the past 15 times to send to those who are new to Python
Python> list> append () and extend ()> append: list is added | extend: list elements are added | + = to add list
A story that struggled to handle the Python package of PocketSphinx
I wanted to solve the ABC164 A ~ D problem with Python
Import modules that are often used when starting the python interpreter
A script that returns 0, 1 attached to the first Python prime number
[python] A note that started to understand the behavior of matplotlib.pyplot
Solution to the problem that the display is corrupted when the .exe command is included in the while loop in wsl2
How to deal with the problem that the current directory moves when Python is executed from Atom
A story that didn't work when I tried to log in with the Python requests module
Avoiding the phenomenon that blank lines are inserted when outputting Python CSV
[Introduction to Python] What is the difference between a list and a tuple?
[Python] How to convert a 2D list to a 1D list
LeetCode 141. Linked List Cycle Solution Example (Python)
[Python] A program that calculates the number of socks to be paired
Extension of Python by C or C ++ (when there are multiple arguments, when passing a list from the Python side)
A function that generates a list with up to 3 prime numbers as elements
How to deal with the problem that build fails when CI / CD of Python Function with AWS Amplify
The NVM Checksum Is Not Valid, a solution to the problem that Intel's wired LAN is not recognized on Linux
10 Python errors that are common to beginners
Python amateurs try to summarize the list ①
How to write a string when there are multiple lines in python
[Python] A program that rounds the score
How to deal with the problem that Japanese characters are garbled when outputting logs using JSON log formatter
How to pass the execution result of a shell command in a list in Python
Try to solve the traveling salesman problem with a genetic algorithm (Python code)
Atcoder Beginner Contest A, B Input summary Python that tends to be a problem
Are Php / Ruby / Python that only runs when the file is called directly
Solution to the problem that you can't activate by putting conda in pyenv
Python script to get a list of input examples for the AtCoder contest
A story that I was addicted to when I made SFTP communication with python
How to get a list of files in the same directory with python
[Python] List Comprehension Various ways to create a list
[python] How to display list elements side by side
[python] Check the elements of the list all, any
Try to calculate a statistical problem in Python
How to clear tuples in a list (Python)
Make a copy of the list in Python
Python Note: When assigning a value to a string
[Algorithm x Python] How to use the list
Note that Python list comprehensions are always confusing