Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Replace Items in List.
#1
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','-','-',"]
Quote
#2
Your list has just one element, string. You need to fix line 4
mcmxl22 likes this post
Quote
#3
I changed line 4 to spaces = ['-' for letter in word].
I also got rid of line 1.
It works!
Quote
#4
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
mcmxl22 likes this post
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Add items from one list to list of lists PUP280 2 285 Mar-28-2020, 08:34 AM
Last Post: PUP280
  Can't seem to figure out how to put all of the lists items from a loop into 1 list Cosmosso 4 353 Feb-21-2020, 02:40 PM
Last Post: Cosmosso
  counting items in a list of number combinations Dixon 2 129 Feb-19-2020, 07:06 PM
Last Post: Dixon
  List items verification for Integer type vintysaw 4 214 Jan-17-2020, 01:56 PM
Last Post: perfringo
  Access list items in Python kamaleon 2 279 Dec-31-2019, 11:10 AM
Last Post: kamaleon
  Remove all \n from end of list items JackMack118 4 7,672 Dec-27-2019, 08:34 AM
Last Post: perfringo
  Removing duplicate list items eglaud 4 236 Nov-22-2019, 08:07 PM
Last Post: ichabod801
  Adding items in a list (using loops?) Seneca260 6 353 Nov-22-2019, 11:34 AM
Last Post: Seneca260
  removing items from a list or group within a for loop. allusernametaken 9 439 Nov-13-2019, 01:58 AM
Last Post: allusernametaken
  How do you replace a word after a match from a list of words in each line of a file? vijju56 1 401 Oct-17-2019, 03:04 PM
Last Post: baquerik

Forum Jump:


Users browsing this thread: 1 Guest(s)