Python - Assignment Creates References, Not Copies

Introduction

In the following example, the list object assigned to the name L is referenced both from L and from inside the list assigned to the name M.

Changing L in place changes what M references, too:

Demo

L = [1, 2, 3] 
M = ['X', L, 'Y']           # Embed a reference to L 
print( M )
L[1] = 0                    # Changes M too 
print( M )

Result

You can avoid sharing objects by copying them explicitly.

For lists, you can always make a top-level copy by using an empty-limits slice:

Demo

L = [1, 2, 3] 
M = ['X', L[:], 'Y']        # Embed a copy of L (or list(L), or L.copy()) 
L[1] = 0                    # Changes only L, not M 
print( L )
print( M )# from   w ww.j  av a2 s . co  m

Result

Slice limits default to 0 and the length of the sequence being sliced.

If both are omitted, the slice extracts every item in the sequence and so makes a top-level copy a new unshared object.

Related Topics