import copy
a=”deepak”
b=1,2,3,4
c=[1,2,3,4]
d={1:10,2:20,3:30}
a1=copy.copy(a)
b1=copy.copy(b)
c1=copy.copy(c)
d1=copy.copy(d)
print "immutable - id(a)==id(a1)",id(a)==id(a1)
print "immutable - id(b)==id(b1)",id(b)==id(b1)
print "mutable - id(c)==id(c1)",id(c)==id(c1)
print "mutable - id(d)==id(d1)",id(d)==id(d1)
I get the following results -
immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) False
mutable - id(d)==id(d1) False
If I perform deepcopy -
a1=copy.deepcopy(a)
b1=copy.deepcopy(b)
c1=copy.deepcopy(c)
d1=copy.deepcopy(d)
results are the same -
immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) False
mutable - id(d)==id(d1) False
If I work on assignment operations -
a1=a
b1=b
c1=c
d1=d
then results are -
immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) True
mutable - id(d)==id(d1) True
Can somebody explain what exactly makes a difference between the copies? Is it something related to mutable & immutable objects? If so, can you please explain it to me?
Below code demonstrates the difference between assignment, shallow copy using the copy method, shallow copy using the (slice) [:] and the deepcopy. Below example uses nested lists there by making the differences more evident.
Normal assignment operations will simply point the new variable towards the existing object. The docs explain the difference between shallow and deep copies:
Here's a little demonstration:
Using normal assignment operatings to copy:
Using a shallow copy:
Using a deep copy: