Exercises
This session asks you to get your feet wet with built-in object fundamentals. As before, a few new ideas may pop up along the way, so be sure to flip to Appendix C when you’re done (and even when you’re not).
The basics. Experiment interactively with the common type operations found in this chapter’s tables. To get you started, bring up the Python interactive interpreter, type the expressions below, and try to explain what’s happening in each case:
2 ** 16 2 / 5, 2 / 5.0 "spam" + "eggs" S = "ham" "eggs " + S S * 5 S[:0] "green %s and %s" % ("eggs", S) ('x',)[0] ('x', 'y')[1] L = [1,2,3] + [4,5,6] L, L[:], L[:0], L[-2], L[-2:] ([1,2,3] + [4,5,6])[2:4] [L[2], L[3]] L.reverse(); L L.sort(); L L.index(4) {'a':1, 'b':2}['b'] D = {'x':1, 'y':2, 'z':3} D['w'] = 0 D['x'] + D['w'] D[(1,2,3)] = 4 D.keys(), D.values(), D.has_key((1,2,3)) [[]], ["",[],(),{},None]Indexing and slicing. At the interactive prompt, define a list named
Lthat contains four strings or numbers (e.g.,L=[0,1,2,3]). Now, let’s experiment with some boundary cases.What happens when you try to index out of bounds (e.g.,
L[4])?What about slicing out of bounds (e.g.,
L[-1000:100])?Finally, how does Python handle it if you try to extract a sequence in reverse—with the lower bound greater than the higher bound (e.g.,
L[3:1])? Hint: try assigning to this slice (L[3:1] = ['?']) and see where the value is put. Do you think this may be the same phenomenon you saw when slicing out of bounds?
Indexing, slicing, and del ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access