Search code examples
pythonlistreplacepycharm

Replacing a item within a list with users input without needing the user to type the index num


I want to take the string input of the user to overwrite an item within a list without changing the placement of the item nor needing the index num of the item being overwritten.

Currently I've gotten a bunch of code to find the item the user would like to replace and code to get the replacing string, I'm just having trouble figuring out how to actually replace the item with the new input. This is my current code:


list = []

while True:
    command = input ("Type add, show, remove, edit or exit: ")
    command = command.strip()
    command = command.capitalize()

    match command:
    case 'Edit' | 'Change':
            action = input("Edit from the To Do list:  ")
            action = action.strip()
            action = action.capitalize()

            if action in list:
                act = input("Editing action " + action + " with: ")
                act = act.strip()
                act = act.capitalize()

                list.append(act)
                print ("Action " + action + " will be replaced with action " + act + ".")
                list.remove(action)

            else:
                print ("Action unidentified. Please try again later.")

I haven't been able to find a working code that does what I want the program to have, and currently I have this code that isn't completely what I want since it removes the item and just adds the string to the bottom of the list. I still regard myself as a beginner in python, and I'm fairly new to PyCharm, so any help would be appreciated.


Solution

  • Here is the simple solution to replace the item with the new string:

    # With the list.index(action), we are getting the index of the input value and 
    # then with list[list.index(action)] = act, we are replacing the value into that index position
    
    
    list[list.index(action)] = act
    
    

    With the list.index(action), we are getting the index of the input value and then with list[list.index(action)] = act, we are replacing the value into that index position

        match command:
            case 'Edit' | 'Change':
                    action = input("Edit from the To Do list:  ")
                    action = action.strip()
                    action = action.capitalize()
    
                    if action in list:
                        act = input("Editing action " + action + " with: ")
                        act = act.strip()
                        act = act.capitalize()
    
                        list[list.index(action)] = act
                        print(list)