I came across this problem while using python.
A=[1,2,3,4,5]
B=A
B.remove(3)
print(B,A)
output
[1, 2, 4, 5] [1, 2, 4, 5]
when I execute this code, 3 is removed from both B and A. I don't want A to be updated,
how can I do that?
I came across this problem while using python.
A=[1,2,3,4,5]
B=A
B.remove(3)
print(B,A)
output
[1, 2, 4, 5] [1, 2, 4, 5]
when I execute this code, 3 is removed from both B and A. I don't want A to be updated,
how can I do that?
When you say B=A
, the list is not copied. Instead, B just points to where the list lives in memory, just like how A does. To change A without changing B, you need to copy the list as B=A.copy()
.
You need to copy A to B. Further reading
A = [1,2,3,4,5]
B = A.copy()
B.remove(3)
print(B, A)