0
a = [ 1, 2, [3,4] ]
b = list(a) # create a shallow copy of a
c = a
print (b is a) # False
print (c is a)

b.append(100) # append element to b
print (b)
print (a) # a is unchanged
print (c)

c.append(100) # append element to c
print (b) # b is unchanged
print (a) 
print (c)

b[2][0] = -100 # modify an element inside b
print (b)
print (a)  # a is changed 
print (c)

c[2][0] = -200
print (b) # b is changed 
print (a) # a is changed 
print (c)

As a beginner in python, I'm not sure what is the meaning of shadow copy, why b.append cannot change a, why c.append cannot change b, why b[2][0] can change a, and why c[2][0] can change b. Thank you!

NightShadeQueen
  • 3,284
  • 3
  • 24
  • 37
uniquegino
  • 1,841
  • 1
  • 12
  • 11
  • "shallow" not "shadow", meaning, the the top level of a nested structure is copied and all subobjects are referenced. – Klaus D. Sep 29 '15 at 02:31

1 Answers1

0

This is happening because shallow copy b contains references to the list [3,4].

So when you do b[2][0] = -100 then since b is having the reference of the nested list hence both a and b gets affected. If you had done deep copy the list [3,4] would be created again in memory and it will be pointed by b Due to above reason c[2][0] also changes b since c is also pointing to the same list as a

Mridul Birla
  • 124
  • 11