Home > Mobile >  list.remove(x): x not in list in Python
list.remove(x): x not in list in Python

Time:01-13

I am trying to make a program that will remove 0 from the list la, but when I try to run the program I get the "Exception has occurred: ValueError list.remove(x): x not in list" error. How do i fix this?

s = '1 0 2 0 3'
la = s.split()
la.remove(0)
print(la)

CodePudding user response:

In your example, you have a list of strings and you are trying to remove an integer.

If you want to remove only the first occurrence you, should replace it with:

la.remove('0')

for all occurnaces:

la[:] = (value for value in la if value != '0')

CodePudding user response:

That is because the list la consists of str element(s) and you are trying to remove integer 0 from it which it does not contain. Reminding you that 0 and '0' are not the same thing, they are int and str respectively.

Let's remove '0' from list la

s = '1 0 2 0 3'
la = s.split()
la.remove("0")
print(la) # ['1', '2', '0', '3']

This as expected removed the first occurrence of '0' in la.

If you rather be interested in making the list la a list containing integers then

la = list(map(int, la))

Is what you're looking for.

  •  Tags:  
  • Related