Luis Anaya
Luis Anaya

Reputation: 303

List index out of range... :(

I've tried to understand why 'if len(w) == 0: continue' is necessary, but I can't really understand it. if I say only look if the 2 word matches wk and if I say the first word must be 'From'. I'm not saying that the phrase has more than 0 words?

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

f = open ('mbox.txt')
wk = ['Sun', 'Mon', 'Tues', 'Wed', 'Thu', 'Fri', 'Sat']

for l in f :
    w = l.split()
    if len(w) == 0: continue #why is this necessary????


    if w[0] != ('From'): continue # si la primera palabra es un "from", pues pasa hacia delate

    if w[2]  in wk :
        print (w[2])

Thanks for your help :)

Upvotes: 1

Views: 144

Answers (2)

PeterE
PeterE

Reputation: 5855

Consider the following points:

  • You do not know how many words there are in a line.
  • You can only access the i-th entry of a list if there are at least i entries in that list (otherwise you will get an index out of range error).

Thus if you want to check if the 3rd entry (i.e. words[2]) of a list has a particular value you first have to guarantee that there are at least 3 entries in that list (i.e. something like len(words) >= 3) before you can check if the value of that word matches your expectation (i.e. words[2] == 'some-value').

Upvotes: 3

Austin
Austin

Reputation: 26037

This occurs when there is no third element in the list. I'm not clear why you're checking for the third element (I assume it's second element).

You can do:

for l in f:
    w = l.split()
    if len(w) >= 2 and w[0] == 'From' and w[1] in wk:
        print(w[1])

Now this prints second word in a line from file if that line starts with 'From' and the second word is available in wk.

Upvotes: -1

Related Questions