12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

This effect usually becomes important only in larger programs, and shared referencesare often exactly what you want. If they’re not, you can avoid sharing objectsby copying them explicitly. For lists, you can always make a top-level copy by usingan empty-limits slice:>>> L = [1, 2, 3]>>> M = ['X', L[:], 'Y'] # Embed a copy of L>>> L[1] = 0 # Changes only L, not M>>> L[1, 0, 3]>>> M['X', [1, 2, 3], 'Y']Remember, slice limits default to 0, and the length of the sequence being sliced; ifboth are omitted, the slice extracts every item in the sequence, and so makes a toplevelcopy (a new, unshared object).Repetition Adds One Level DeepSequence repetition is like adding a sequence to itself a number of times. That’s true,but when mutable sequences are nested, the effect might not always be what youexpect. For instance, in the following example X is assigned to L repeated four times,whereas Y is assigned to a list containing L repeated four times:>>> L = [4, 5, 6]>>> X = L * 4 # Like [4, 5, 6] + [4, 5, 6] + ...>>> Y = [L] * 4 # [L] + [L] + ... = [L, L,...]>>> X[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]>>> Y[[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6]]Because L was nested in the second repetition, Y winds up embedding referencesback to the original list assigned to L, and so is open to the same sorts of side effectsnoted in the last section:>>> L[1] = 0 # Impacts Y but not X>>> X[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]>>> Y[[4, 0, 6], [4, 0, 6], [4, 0, 6], [4, 0, 6]]The same solutions to this problem apply here as in the previous section, as this isreally just another way to create the shared mutable object reference case. If youremember that repetition, concatenation, and slicing copy only the top level of theiroperand objects, these sorts of cases make much more sense.192 | Chapter 9: Tuples, Files, and Everything Else

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!