read the error messages

The next step of my crossword-puzzle-answer finder is to modify the search by letter function to find a letter by a selected index. I’m a little shaky on indexes, so I thought I’d test out if Python could look inside each item inside the list and get a slice of the string.

for item in words_list:
if item[2] == ‘x’:
>>> Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
File “/home/pi/”, line 32, in <module>
IndexError: string index out of range

Well that was weird. Why was it doing that? I should be able to get a slice of each list item with that. So I sit and think about it and wonder what is wrong. I go make dinner, fix a computer, and watch some videos. Then it hits me, how about I actually read the error?

IndexError: string index out of range

This error is thrown when you ask Python for the index outside the range of a string, meaning when I’m asking for the [2]’d index of the item, I’m asking to match the third character.

words.txt contains 2 letter words. In fact, the first word in words.txt is ‘aa’, which is a kind of lava. Derp.

Time to break out some of that exception handling I’ve been meaning to try:

for item in words_list:
if item[2] == 'x':
print(item, end=' ')
except IndexError:
>>> anxieties anxiety anxious...

Now when the test loop hits an IndexError because a word is too short, it shrugs and moves on rather than raising the exception and bringing everything crashing down.

Like what you read? Give Benton Smith a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.