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:
L = [1, 2, 3] M = ['X', L, 'Y'] # Embed a reference to L print( M ) L = 0 # Changes M too print( M )
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:
L = [1, 2, 3] M = ['X', L[:], 'Y'] # Embed a copy of L (or list(L), or L.copy()) L = 0 # Changes only L, not M print( L ) print( M )# w w w .j a v a2 s . c o m
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.