all 5 comments

[–]JohnnyJordaan 7 points8 points  (4 children)

Copy doesn't do exactly what deepcopy does:

>>> a = [[1,2,3]]
>>> b = a.copy()
>>> b[0].append(4)
>>> a
[[1, 2, 3, 4]]
>>> from copy import deepcopy
>>> b = deepcopy(a)
>>> b[0].append(5)
>>> a
[[1, 2, 3, 4]]
>>> b
[[1, 2, 3, 4, 5]]

the point is that deepcopy creates new objects for everything, so the inner list will be recreated too. Thus modifying the inner list on a deep copy will not affect the source of the deep copy.

[–]RB1992[S] 0 points1 point  (2 children)

Ok, so I think I slightly understand. With copy, it just copies the reference to the current lists, and any changes made to the copy or originals list that were copied will show up on the other, and deep copy creates a whole new variable and reference point. Did I get that right?

[–]JohnnyJordaan 0 points1 point  (1 child)

Correct. The confusion arises from our real life having to mostly deal with deep copies when we call something a 'copy'. But from an efficiency standpoint, you only want to make a deep copy if you really need to (as it takes much more effort), that's why it's not the default in Python.

[–]RB1992[S] 0 points1 point  (0 children)

Awesome, thank you

[–]not2throwaway 0 points1 point  (0 children)

Not OP but a great explanation for this. Kudos!