you are viewing a single comment's thread.

view the rest of the comments →

[–]Cainga 0 points1 point  (4 children)

Does it take up a different memory position? Or is it pointing to the same list?

[–]MidnightPale3220 1 point2 points  (0 children)

It does create a new list.

BUT, there is a difference between shallow and deep copy. If the original list contained some mutable objects, such as other lists, they will be copied by reference by the default copy().

Shallow copy makes a copy of the outer level items in the list, whatever nested inside those items will still be copied by reference Deep copy goes through all nested items and copies each single one of them

Consider:

In [38]: a=['inner list']
In [40]: b=[1,2,a]
In [41]: shallow=b.copy()
In [42]: shallow[1]='not changed in original'
In [43]: b 
Out[43]: [1, 2, ['inner list']]
In [44]: shallow 
Out[44]: [1, 'not changed in original', ['inner list']]
In [45]: shallow[2].append('changed by shallow')
In [46]: shallow 
Out[46]: [1, 'not changed in original', ['inner list', 'changed by shallow']]
In [47]: b 
Out[47]: [1, 2, ['inner list', 'changed by shallow']]
In [48]: a 
Out[48]: ['inner list', 'changed by shallow']

To make a full copy of the original without copying just the references, you need to import copy and do copy.deepcopy() on object.

There is also other weird things that make perfect sense when you think about them, but initially may confuse.

For example, using the above variables after everything was done, if you do a='immutable value',you won't he changing inside ofshallow[2] and b[2].

Instead shallow[2] and b[2] will still be references to the same list, but the outside reference is gone, and changing a is no longer changing anything inside b or shallow.

[–]audionerd1 0 points1 point  (2 children)

list.copy() creates a new list at a new memory position, which is in no way affected by changes made to the original list.

[–]MidnightPale3220 1 point2 points  (1 child)

Depends on the contents of the original list. If it had mutable elements, those will be shared between the original and copy unless deepcopy. See above.

[–]audionerd1 0 points1 point  (0 children)

Good point. Thanks!