16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

84 CHAPTER 5 ■ CONDITIONALS, LOOPS, AND SOME OTHER STATEMENTS<br />

>>> values = 1, 2, 3<br />

>>> values<br />

(1, 2, 3)<br />

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

>>> x<br />

1<br />

This is particularly useful when a function or method returns a tuple (or other sequence or<br />

iterable object); let’s say that you want <strong>to</strong> retrieve (and remove) an arbitrary key-value pair<br />

from a dictionary. You can then use the popitem method, which does just that, returning the<br />

pair as a tuple. Then you can unpack the returned tuple directly in<strong>to</strong> two variables:<br />

>>> scoundrel = {'name': 'Robin', 'girlfriend': 'Marion'}<br />

>>> key, value = scoundrel.popitem()<br />

>>> key<br />

'girlfriend'<br />

>>> value<br />

'Marion'<br />

This allows functions <strong>to</strong> return more than one value, packed as a tuple, easily accessible<br />

through a single assignment. The sequence you unpack must have exactly as many items as the<br />

targets you list on the left of the = sign; otherwise <strong>Python</strong> raises an exception when the assignment<br />

is performed.<br />

Chained Assignments<br />

Chained assignments are used as a shortcut when you want <strong>to</strong> bind several variables <strong>to</strong> the<br />

same value. This may seem a bit like the simultaneous assignments in the previous section,<br />

except that here you are only dealing with one value:<br />

x = y = somefunction()<br />

which is the same as<br />

y = somefunction()<br />

x = y<br />

Note that the preceding statements may not be the same as<br />

x = somefunction()<br />

y = somefunction()<br />

For more information, see the section about the identity opera<strong>to</strong>r (is), later in this chapter.<br />

Augmented Assignments<br />

Instead of writing x = x + 1, you can just put the expression opera<strong>to</strong>r (in this case +) before the<br />

assignment opera<strong>to</strong>r (=) and write x += 1. This is called an augmented assignment, and it works<br />

with all the standard opera<strong>to</strong>rs, such as *, /, %, and so on:

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

Saved successfully!

Ooh no, something went wrong!