Learning Python - Mark Lutz [589]
>>> D
{'b': 2, 'd': 4, 'a': 1, 'c': 3}
>>>
>>> L = [0, 1]
>>> L[2]
Traceback (innermost last):
File " IndexError: list index out of range >>> L[2] = 3 Traceback (innermost last): File " IndexError: list assignment index out of range Generic operations. Question answers: The + operator doesn’t work on different/mixed types (e.g., string + list, list + tuple). + doesn’t work for dictionaries, as they aren’t sequences. The append method works only for lists, not strings, and keys works only on dictionaries. append assumes its target is mutable, since it’s an in-place extension; strings are immutable. Slicing and concatenation always return a new object of the same type as the objects processed:>>> "x" + 1 Traceback (innermost last): File " TypeError: illegal argument type for built-in operation >>> >>> {} + {} Traceback (innermost last): File " TypeError: bad operand type(s) for + >>> >>> [].append(9) >>> "".append('s') Traceback (innermost last): File " AttributeError: attribute-less object >>> >>> list({}.keys()) # list needed in 3.0, not 2.6 [] >>> [].keys() Traceback (innermost last): File " AttributeError: keys >>> >>> [][:] [] >>> ""[:] '' String indexing. This is a bit of a trick question—Because strings are collections of one-character strings, every time you index a string, you get back a string that can be indexed again. S[0][0][0][0][0] just keeps indexing the first character over and over. This generally doesn’t work for lists (lists can hold arbitrary objects) unless the list contains strings:>>> S = "spam" >>> S[0][0][0][0][0] 's' >>> L = ['s', 'p'] >>> L[0][0][0] 's' Immutable types. Either of the following solutions works. Index assignment doesn’t, because strings are immutable:>>> S = "spam" >>> S = S[0] + 'l' + S[2:] >>> S 'slam' >>> S = S[0] + 'l' + S[2] + S[3] >>> S 'slam' (See also the Python 3.0 bytearray string type in Chapter 36—it’s a mutable sequence of small integers that is essentially processed the same as a string.) Nesting. Here is a sample:>>> me = {'name':('John', 'Q', 'Doe'), 'age':'?', 'job':'engineer'} >>> me['job'] 'engineer' >>> me['name'][2] 'Doe' Files. Here’s one way to create and read back a text file in Python (ls is a Unix command; use dir on Windows):# File: maker.py file = open('myfile.txt', 'w') file.write('Hello file world!\n') # Or: open().write() file.close() # close not always needed # File: reader.py file = open('myfile.txt') # 'r' is default open mode print(file.read()) # Or print(open().read()) % python maker.py % python reader.py Hello file world! % ls -l myfile.txt -rwxrwxrwa 1 0 0 19 Apr 13 16:33 myfile.txt Part III, Statements and Syntax See Test Your Knowledge: Part III Exercises in Chapter 15 for the exercises. Coding basic loops. As you work through this exercise, you’ll wind up with code that looks like the following:>>> S = 'spam' >>> for c in S: ... print(ord(c)) ... 115 112 97 109 >>> x = 0 >>> for c in S: x += ord(c) # Or: x = x + ord(c) ... >>> x 433 >>> x = [] >>> for c in S: x.append(ord(c)) ... >>> x [115, 112, 97, 109] >>> list(map(ord, S)) # list() required in 3.0, not 2.6 [115, 112, 97, 109] Backslash characters. The example prints the bell character (\a) 50 times; assuming your machine can handle it, and when it’s run outside of IDLE, you may get a series of beeps (or one sustained tone, if your machine is fast enough). Hey—I warned you. Sorting dictionaries. Here’s one way to work through this exercise (see Chapter 8 or Chapter 14 if this doesn’t make sense). Remember, you really do have to split up the keys and sort calls like this because sort returns None. In Python 2.2 and later, you can iterate through dictionary keys directly without calling keys (e.g., for key in D:), but the keys list will not be sorted like it is by this code. In more recent Pythons, you can achieve the same