0

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?

  • Hey! A good source to read upon what you encounter is this: https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment – neaAlex Jul 12 '22 at 12:06

2 Answers2

1

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().

-1

You need to copy A to B. Further reading

A = [1,2,3,4,5]
B = A.copy()
B.remove(3)
print(B, A)
eightlay
  • 423
  • 2
  • 9