简体   繁体   中英

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.

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.

Works with 'hi' as input too.

list = [1, 2, 3, "hi", 5]


by_index = input('Do you want to delete an index: yes/no ')
bool_index = False
x = input("enter the value/index to be deleted ")


if by_index.lower() == 'yes':
    del(list[int(x)])

elif by_index.lower() == 'no':
    if x.isdigit():
        x = int(x)
    del(list[list.index(x)])

else:
    print('Error!')


print(list)

[1, 2, 3, 5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM