I want to make the list not affect each other.

Asked 2 years ago, Updated 2 years ago, 21 views

ex = [1]
EX = ex
EX[0] = ex[0] + 1

When you do it as above, both EX[0] and ex[0] will be 2. I want EX[0] to be 2, but ex[0] to be maintained at 1.

python

2022-09-21 11:50

1 Answers

Both ex and EX are caused by pointing to the same list object.
You can clone a list element to create a new list object.

We usually use two methods.

copyHow to use the method

EX = ex.copy()

How to use slicing

EX = ex[:]

If the list contains objects of different mutable types, you may need deepcopy.
deepcopy recursively copies all elements within the list.

import copy

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

a[0][0] = 0

print(a)  # [[0, 2], [3, 4]]
print(b)  # [[0, 2], [3, 4]]
print(c)  # [[1, 2], [3, 4]]


2022-09-21 11:50

If you have any answers or tips


© 2025 OneMinuteCode. All rights reserved.