Chris Schell Chris Schell - 4 months ago 9
Python Question

Scanning a list - IndexError: list index out of range

I have created a Hangman game that has one bug: if you guess the same letter twice it will break. I have created a list of every alphabet letter and when the player guesses that letter it will be removed from the list, which displays the remaining characters available to guess. This is accomplished through the .remove method, which will break if the character has already been removed from a previous guess.

I have attempted to nest this method in a for loop that will scan the alphabet list and check the user's guess for a match in the list and remove it. If it has already been guessed, then nothing will happen. The error i receive is an index error, presumably for the length of the guess. My confusion comes from the fact that I can accomplish this exact same task directly below when scanning the hangman word to match the player's guess. Please see the abridged code below:

# Play begins and player guesses a letter
player_word = ['_ '] * len(cpu_word)
player_word2 = ['_'] * len(cpu_word)
alphabet = ['a','b',etc.]
print 'You have 10 guesses left'

# Determines if the guess is correct
for count in range(10)[::-1]:
guess = raw_input(str('Guess a letter: '))
# This is the previous method that creates a bug:/
# alphabet.remove(guess)
for e in xrange(len(alphabet)):
if alphabet[e] == guess:
alphabet.remove(guess)
for i in xrange(len(cpu_word)):
if cpu_word[i] == guess:
player_word [i] = cpu_word [i]
print 'Correct!'


I have two questions. The first is can someone please explain this error to me, specifically why it works for scanning the hangman word but does not work for scanning the list.

And secondly, can anyone provide a solution for this problem.

I am new to coding so any info is greatly appreciated!

Thanks

Wso Wso
Answer

Your problem is that after you remove an item from the array, it now has one less item, meaning that you can't go to the former end of the array. If your array of letters is 26 long, and you remove one letter, you can't access the 26th element anymore, because the array now only has 25 elements. After you guess correctly, you could just break, like so:

for e in xrange(len(alphabet)):
    #print alphabet[e], e
    if alphabet[e] == guess:
        alphabet.remove(guess)
        break

However you could just uncomment the line above, and check if it is in the array before removing it, like this:

for count in range(10)[::-1]:
guess = raw_input(str('Guess a letter: '))
if(guess in alphabet):
    """"This is the previous method that creates a bug:/"""
    alphabet.remove(guess)
    for i in xrange(len(cpu_word)):
        if cpu_word[i] == guess:
            player_word [i] = cpu_word [i]
            print 'Correct!'