0

Please help me to understand the result of Example#1-B:

Example#1-A:

ref=[3,5,9]
c=ref[:]
c[1]=0
# c equals to [3,0,9], and ref equals to [3, 5, 9]

Example#1-B:

ref=[[1,2],[3,4]]
c=ref[:]
c[0][1]=0
# c equals to [[1, 0], [3, 4]], and ref equals to [[1, 0], [3, 4]]

Example#2-A:

ref=[3,5,9]
c=copy.deepcopy(ref)
c[1]=0
# c equals to [3, 0, 9], and ref equals to [3, 5, 9]

Example#2-B:

ref=[[1,2],[3,4]]
c=copy.deepcopy(ref)
c[0][1]=0
# c equals to [[1,0],[3,4]], and ref equals to [[1,2],[3,4]]
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
S. Lee
  • 33
  • 4
  • Possible duplicate of [What exactly is the difference between shallow copy, deepcopy and normal assignment operation?](https://stackoverflow.com/questions/17246693/what-exactly-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignm) – ShadowRanger Oct 25 '18 at 00:57

1 Answers1

0

lists are mutables. line c=ref[:] in example 1-B is copying the reference of the sublists of refin the new list c Hence you access to the same sublists from ref and c

Valentino
  • 7,291
  • 6
  • 18
  • 34
  • The line c=ref[:] in example 1-A is also copying the reference of the list ref. Then, the ref should be changed to [3,0,9] instead of [3,5,9]. Which is not the case. Am I missing something here? – S. Lee Oct 25 '18 at 01:10
  • Because integer are immutable. In case 1-A the `c=ref[:]` creates a new list holding copies (of immutables), and not references (of mutables). The copy.deepcopy method is used to create copies of mutables instead of references to them (this explains the difference between 1-B and 2-B). Hope to have been a little more clear. – Valentino Oct 25 '18 at 01:18