1/22/2014

(Python study) deep copy and shallow copy (example source code)

#this is Shallow copy
a=[1, 2, 3]
b=a
a[0] = 38
print(a, b)
print(id(a), id(b))
#[38, 2, 3] [38, 2, 3]
#4320547040 4320547040

#this is deep copy
b = a[:]
print(id(a), id(b))
#4320427976 4320427472

a[0] = 50;
print(a, b)
#[50, 2, 3] [38, 2, 3]

import copy

a=[1,2,3]
b = copy.deepcopy(a)
a[0] = 38
print(a, b)
[38, 2, 3] [1, 2, 3]



No comments:

Post a Comment