12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Multiple-target assignmentsThe fifth line in Table 11-1 shows the multiple-target form of assignment. In thisform, <strong>Python</strong> assigns a reference to the same object (the object farthest to theright) to all the targets on the left. In the table, the names spam and ham are bothassigned references to the same string object, 'lunch'. The effect is the same as ifwe coded ham = 'lunch' followed by spam = ham, asham evaluates to the originalstring object (i.e., not a separate copy of that object).Augmented assignmentsThe last line in Table 11-1 is an example of augmented assignment—a shorthandthat combines an expression and an assignment in a concise way. Sayingspam += 42, for example, has the same effect as spam = spam + 42, but the augmentedform requires less typing, and is generally quicker to run. There’s oneaugmented assignment statement for every binary expression operator in <strong>Python</strong>.Sequence AssignmentsWe’ve already used basic assignments in this book. Here are a few simple examplesof sequence-unpacking assignments in action:% python>>> nudge = 1>>> wink = 2>>> A, B = nudge, wink # Tuple assignment>>> A, B # Like A = nudge; B = wink(1, 2)>>> [C, D] = [nudge, wink] # List assignment>>> C, D(1, 2)Notice that we really are coding two tuples in the third line in this interaction—we’ve just omitted their enclosing parentheses. <strong>Python</strong> pairs the values in the tupleon the right side of the assignment operator with the variables in the tuple on the leftside, and assigns the values one at a time.Tuple assignment leads to a common coding trick in <strong>Python</strong> that was introduced in asolution to the exercises from Part II. Because <strong>Python</strong> creates a temporary tuple thatsaves the original values of the variables on the right while the statement runs,unpacking assignments are also a way to swap two variables’ values without creatinga temporary variable of your own—the tuple on the right remembers the prior valuesof the variables automatically:>>> nudge = 1>>> wink = 2>>> nudge, wink = wink, nudge # Tuples: swaps values>>> nudge, wink # Like T = nudge; nudge = wink; wink = T(2, 1)Assignment Statements | 219

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

Saved successfully!

Ooh no, something went wrong!