15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Another way of assigning multiple variables is using what we shall call the "multuple" assignment. This<br />

is not an official <strong>Python</strong> term, but we use "multuple" here because when assigning variables this way,<br />

the objects on both sides of the equal sign are tuples, a <strong>Python</strong> standard type we introduced in Section<br />

2.8.<br />

>>> x, y, z = 1, 2, 'a string'<br />

>>> x<br />

1<br />

>>> y<br />

2<br />

>>> z<br />

'a string'<br />

In the above example, two integer objects (with values 1 and 2) and one string object are assigned to x,<br />

y, and z respectively. Parentheses are normally used to denote tuples, and although they are optional,<br />

we recommend them anywhere they make the code easier to read:<br />

>>> (x, y, z) = (1, 2, 'a string')<br />

If you have ever needed to swap values in other languages like C, you will be reminded that a<br />

temporary variable, i.e., tmp, is required to hold one value while the other is being exchanged:<br />

/* swapping variables in C */<br />

tmp = x;<br />

x = y;<br />

y = tmp;<br />

In the above C code fragment, the values of the variables x and y are being exchanged. The tmp variable<br />

is needed to hold the value of one of the variables while the other is being copied into it. After that step,<br />

the original value kept in the temporary variable can be assigned to the second variable.<br />

One interesting side effect of <strong>Python</strong>'s "multuple" assignment is that we no longer need a temporary<br />

variable to swap the values of two variables.<br />

# swapping variables in <strong>Python</strong><br />

>>> x, y = 1, 2<br />

>>> x<br />

1<br />

>>> y<br />

2<br />

>>> x, y = y, x<br />

>>> x<br />

2<br />

>>> y<br />

1<br />

Obviously, <strong>Python</strong> performs evaluation before making assignments.

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

Saved successfully!

Ooh no, something went wrong!