Home > Net >  How does list() in python works for below scenario? [duplicate]
How does list() in python works for below scenario? [duplicate]

Time:09-23

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

This is because you write B=list(A) see example:

A = [12, 34, [56]]
B = list(A)
print(id(B))
# 140206999437504

print(id(A))
# 140206999413120

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

they have different address but if you use B = A you get what you want.

A = [12, 34, [56]]
B = A
print(id(B))
# 140206999354368

print(id(A))
# 140206999354368
A[2][0] = 89
A[1] = 70
print(B)
# [12, 70, [89]]
  • Related