pythonpython-3.xlistremove-method

How can I delete integers from list (of integers and strings) by taking which value to delete from user input?


I am doing a menu driven program in python to insert and delete items in a list. I have a list containing integers and strings. I want to delete integer.

So I take input from user as

list = [1, 2, 3, "hi", 5]
x = input("enter the value to be deleted")
# input is given as 2 
list.remove(x)

But it gives me a ValueError

I typecasted the input to int and it worked for integers but not for the string.


Solution

  • It gives you an error because you want to remove int, but your input is str. Your code will work only if input is 'hi'.

    Try this:

    arr = [1, 2, 3, "hi", 5]
    x = input("enter the value to be deleted")  # x is a str!
    
    if x.isdigit():  # check if x can be converted to int
        x = int(x)  
    
    arr.remove(x)  # remove int OR str if input is not supposed to be an int ("hi")
    

    And please don't use list as a variable name, because list is a function and a data type.