Python Forum

Full Version: Replace Items in List.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to replace items in a list based on the index. I don't understand why I'm getting the 'index out of range' error.
This is what I have:
spaces = []
word = "word"
guess = "o"
spaces.append("'-'," * len(word))
letter_list = list(word)
locate = letter_list.index(guess)

print(spaces)
spaces[locate] = guess
print(spaces)
This is the error:
Error:
["'-','-','-','-',"] Traceback (most recent call last): File "tst.py", line 9, in <module> spaces[locate] = guess IndexError: list assignment index out of range
This is the desired output:
Output:
["'-','-','-','-',"] ["'-','o','-','-',"]
Your list has just one element, string. You need to fix line 4
I changed line 4 to spaces = ['-' for letter in word].
I also got rid of line 1.
It works!
If you use exception testing, you can handle guess being incorrect:
word = 'word'
spaces = list('-' * len(word))
guess = 'o'

try:
    locate = word.index(guess)
    spaces[locate] = guess
    print(f"{spaces}")
except ValueError:
    print(f"guess {guess} not in word")
output:
Output:
['-', 'o', '-', '-']
you can put it all in a function to complete