1

I tried:

A = [1,2,3]
B = A
B[0] = A[0]*3

should give:

B == [3,2,3]
True
A == [1,2,3]
True

but what it really does:

B == [3,2,3]
A == [3,2,3]

how do I copy A over in B without keeping A linked to B? Thanks for your help.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
Perm. Questiin
  • 429
  • 2
  • 9
  • 21

1 Answers1

2

This is because you are only pointing the reference to B, without making a copy at all. Instead do the following to actually create a copy.

A = [1,2,3]
B = A[:]

This will work if there are no referenced variables. If you don't want that behaviour, then use a deep_copy method as below

B = copy.deepcopy(A)

Then if you change A, it won't change B

A. N. Other
  • 392
  • 4
  • 14