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.

4. Tuple assignment. The values of X and Y are swapped. When tuples appear on theleft and right of an assignment symbol (=), <strong>Python</strong> assigns objects on the right totargets on the left according to their positions. This is probably easiest to understandby noting that the targets on the left aren’t a real tuple, even though theylook like one; they are simply a set of independent assignment targets. The itemson the right are a tuple, which gets unpacked during the assignment (the tupleprovides the temporary assignment needed to achieve the swap effect):>>> X = 'spam'>>> Y = 'eggs'>>> X, Y = Y, X>>> X'eggs'>>> Y'spam'5. Dictionary keys. Any immutable object can be used as a dictionary key—includingintegers, tuples, strings, and so on. This really is a dictionary, even though some ofits keys look like integer offsets. Mixed-type keys work fine, too:>>> D = {}>>> D[1] = 'a'>>> D[2] = 'b'>>> D[(1, 2, 3)] = 'c'>>> D{1: 'a', 2: 'b', (1, 2, 3): 'c'}6. Dictionary indexing. Indexing a nonexistent key (D['d']) raises an error; assigningto a nonexistent key (D['d']='spam') creates a new dictionary entry. On the otherhand, out-of-bounds indexing for lists raises an error too, but so do out-of-boundsassignments. Variable names work like dictionary keys; they must have alreadybeen assigned when referenced, but are created when first assigned. In fact, variablenames can be processed as dictionary keys if you wish (they’re made visiblein module namespace or stack-frame dictionaries):>>> D = {'a':1, 'b':2, 'c':3}>>> D['a']1>>> D['d']Traceback (innermost last):File "", line 1, in ?KeyError: d>>> D['d'] = 4>>> D{'b': 2, 'd': 4, 'a': 1, 'c': 3}>>>>>> L = [0, 1]>>> L[2]Traceback (innermost last):File "", line 1, in ?IndexError: list index out of range>>> L[2] = 3Traceback (innermost last):File "", line 1, in ?IndexError: list assignment index out of rangePart II, Types and Operations | 651

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

Saved successfully!

Ooh no, something went wrong!