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.

B RAINB UILDERChapter Quiz1. Consider the following three statements. Do they change the value printed for A?A = "spam"B = AB = "shrubbery"2. Consider these three statements. Do they change the value of A?A = ["spam"]B = AB[0] = "shrubbery"3. How about these—is A changed?A = ["spam"]B = A[:]B[0] = "shrubbery"Quiz Answers1. No: A still prints as "spam". When B is assigned to the string "shrubbery", all thathappens is that the variable B is reset to point to the new string object. A and Binitially share (i.e., reference, or point to) the same single string object "spam",but two names are never linked together in <strong>Python</strong>. Thus, setting B to a differentobject has no effect on A. The same would be true if the last statement here wasB=B+'shrubbery', by the way—the concatenation makes a new object for itsresult, which is then assigned to B only. We can never overwrite a string (ornumber, or tuple) in-place, because strings are immutable.2. Yes: A now prints as ["shrubbery"]. Technically, we haven’t really changed eitherA or B; instead, we’ve changed part of the object they both reference (point to) byoverwriting that object in-place through the variable B. Because A references thesame object as B, the update is reflected in A as well.3. No: A still prints as ["spam"]. The in-place assignment through B has no effectthis time because the slice expression made a copy of the list object before it wasassigned to B. After the second assignment statement, there are two different listobjects that have the same value (in <strong>Python</strong>, we say they are ==, but not is). Thethird statement changes the value of the list object pointed to by B, but not thatpointed to by A.122 | Chapter 6: The Dynamic Typing Interlude

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

Saved successfully!

Ooh no, something went wrong!