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.
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.
copy
How 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]]
© 2025 OneMinuteCode. All rights reserved.