-2
A = [12, 34, [56]]
B = list(A)
A[2][0] = 89
A[1] = 70
print(B)

Output:

B is [12,34,[89]]

and not [12,70,[89]]

I am new to python and I don't get why B is [12, 34, [89]] and not [12, 70, [89]]? B is having different memory than A, why only B's index 3 is getting updated with A's change?

2 Answers2

0

since B = A and B = list(A) is different. list() copies values of A . it is same as in Javascript B = [...A] for deep copying

Emin GENC
  • 11
  • 3
0

In Python, there are three kinds of assignment, shallow copy and deep copy list(A) is equivalent to B=A, B doesn't create a new memory space, it's just a reference to A So modifying A will affect B You can check if the memory address of A and B are the same by id

The other is a shallow copy, by B=A[:], B creates a new memory, and using the id, we can find that it does not point to the same piece of memory At this point, modifying B does not affect A, but because it is a shallow copy, only one layer is copied, and when the nested [56] in A is modified, B will also change

Using deep copy B=copy.deepcopy(A) avoids it completely

Asolmn
  • 1