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).

  1. 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]
  2. Indexing and slicing. At the interactive prompt, define a list named L that contains four strings or numbers (e.g., L=[0,1,2,3]). Now, let’s experiment with some boundary cases.

    1. What happens when you try to index out of bounds (e.g., L[4])?

    2. What about slicing out of bounds (e.g., L[-1000:100])?

    3. 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?

  3. Indexing, slicing, and del ...

Get Learning Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.