Chapter 8 Lists Exercises

by Elliott Hauser

09 Feb 2016

Exercise 1:

Write a function called chop that takes a list and modifies it, removing the first and last elements, and returns None. call it several times to check your work.

Exercise 2:

fhand = open('mbox-short.txt')
count = 0
for line in fhand:
    words = line.split()
    # print 'Debug:', words
    if len(words) == 0 : continue
    if words[0] != 'From' : continue
    print(words[2])

Figure out which line of the above program is still not properly guarded. See if you can construct a text file which causes the program to fail and then modify the program so that the line is properly guarded and test it to make sure it handles your new text file.

**Exercise 3: **

Rewrite the guardian code in the above example without two if statements. Instead, use a compound logical expression using the and logical operator with a single if statement.

Elliott Hauser is a PhD Student in information science at UNC Chapel Hill. He's hacking education as one of the cofounders of Trinket.io. Find Elliott Hauser on Twitter, Github, and on the web.