0

Here is what I am trying to do:

  1. Pick a random word from a list

  2. Ask the user of a word to replace it with

  3. Print out the list with the word replaced

So I have the random word picker part finished, but I don't know how to replace the word with the input. I thought I could use the .replace() function, but it's a list. Here is the code:

import random

all_lists = ['beans','peaches','yogurt','eggs','pizza']
for x in all_lists:
    print(x)

appending_list = input("Would you like to replace a word? Yes or No?")

if appending_list == ("Yes"):
    random = random.choice(all_lists) #this picks the random word
    replace_word = input("What would would you like to replace the word with?")
    all_lists_replace = all_lists.replace(random, replace_word)
    print(all_lists_replace)

if appending_list == ("No"):
    exit()
wuflpck
  • 5
  • 2
  • Does this answer the question? https://stackoverflow.com/questions/1540049/replace-values-in-list-using-python – gshpychka Nov 16 '21 at 19:08
  • Maybe you could do an approach instead where you generate an random int as index to choose a random word from the list and then set the list element at the index with the input. – Cade Weiskopf Nov 16 '21 at 19:11

2 Answers2

3

Use index

from random import randrange

all_lists = ['beans','peaches','yogurt','eggs','pizza']
for x in all_lists:
    print(x)

appending_list = input("Would you like to replace a word? Yes or No?")

if appending_list == ("Yes"):
    idx = randrange(len(all_lists))
    replace_word = input("What would would you like to replace the word with?")
    all_lists[idx] = replace_word
    print(all_lists)
balderman
  • 22,927
  • 7
  • 34
  • 52
0

Instead of selecting a random choice from the list, I suggest you select a random index. That way, you can replace that element of the list by simply assigning the user's input to that index of the list.

appending_list = input("Would you like to replace a word? Yes or No?")

if appending_list == ("Yes"):
    ix = random.randint(0, len(all_lists))
    replace_word = all_lists[ix]
    replacement = input(f"What should I replace {replace_word} with?")
    all_lists[ix] = replacement
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70