0

How do I append a list based on user input? I have made a menu and used ifelif statements. When running the script I select "2" to add a name to the list, after inputting the name, I press "1" to display the list. No matter how many names I add I am only able too to view the last inputted name.

**menu = """


 mylist = ['Nick', 'Robert', 'Deondre,']
while True:
selection = input(menu).strip()
if selection == "0":
    print("Thank you for using guest list manager.")
    break
elif selection == "1":
    print("List of guests.\n")
    print(mylist)
elif selection == "2":
    mylist = input('Please enter a name to be added: ') 
elif selection == "3":
    mylist = input("Please enter a name to be deleted: ")
    mylist.append(mylist)
else:
    print("Please select 0, 1, 2, or 3")**

1 Answers1

0

You are overwriting your original list. Use a separate variable for saving input and then append it to your original list.

Instead of this:

elif selection == "2":
    # You are replacing your list
    mylist = input('Please enter a name to be added: ') 

Write this:

elif selection == "2":
    # Save input in a variable
    new_name = input('Please enter a name to be added: ')
    # Append it at the end
    mylist.append(new_name)

Similarly for selection 3 (deletion), you need to save the input in a variable and use that to delete element from the list. list.append() is for adding element(s) at the end of a list, not for deletion. For deletion you can use list.remove() instead.

elif selection == "3":
    # Save input in a variable
    name_to_be_deleted = input("Please enter a name to be deleted: ")
    # Save input in a variable
    mylist.remove(name_to_be_deleted)

Reference: SO answer comparing deletion methods

Ajit Panigrahi
  • 752
  • 10
  • 27