Nisarg
Nisarg

Reputation: 23

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.

Upvotes: 2

Views: 1588

Answers (2)

innicoder
innicoder

Reputation: 2688

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]

Upvotes: 0

Ivan Vinogradov
Ivan Vinogradov

Reputation: 4483

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.

Upvotes: 6

Related Questions