Home > Software engineering >  How to add a specific input to the front a specific list item in Python
How to add a specific input to the front a specific list item in Python

Time:11-13

I wanted to my program display a list and ask the user what list item they completed. After they input that which will be an item in the list, it should insert an "X " in front of it. E.g if the list is [homework, chores] the list should then become [X homework, chores] if the user inputs "homework".


    run = True
    while run:
        input000 = input("Which items do you wish to record as done?")
    # Something the adds X to the front of the chosen list item (from the input)

CodePudding user response:

list_item = ["homework", "chores"]
while True:
    input000 = input("enter something")
    for i in range(len(list_item)):
        if input000 == list_item[i]:
            list_item[i] = f"X {list_item[i]}"

CodePudding user response:

You can search for your object then adjust it:

for item in list_item:
    if item == input000:
        item = 'X '   item

Please, for the future, include your own attempts.

CodePudding user response:

A more Pythonic approach is to use the list's index() method in conjunction with an exception handler to validate the user's input.

You'll also need some way to break out of the loop - perhaps when all items in the list have been marked as "done"

Something like this:

todo_list = ['homework', 'chores']

def todo():
    for e in todo_list:
        if e[0] != 'X':
            yield e

while sum(1 for _ in todo()) > 0:
    print(*todo(), sep='\n')
    item = input('Choose something: ')
    try:
        i = todo_list.index(item)
        todo_list[i] = f'X {item}'
    except ValueError:
        print("\aThat's not in the list")
  • Related