All Python errors
ValueError in Python: unsuitable value
ValueError means the value has a suitable type, but this particular value cannot be used. To fix it, check the value first: for example, make sure an item is in the list before removing it.
Code with the error
basket = ["bread", "milk"]
basket.remove("cheese")
print(basket)
Error message (Python 3.12, last line)
Corrected code
basket = ["bread", "milk"]
if "cheese" in basket:
basket.remove("cheese")
print(basket)
Output
['bread', 'milk']
Common causes
- list.remove() gets an item that is not in the list.
- int() gets text that is not a whole number, such as "ten" or "3.5".
- The number of names on the left differs from the number of values on the right.
- list.index() searches for an item that is absent.
Practise in the course
Lesson: ListsFrequently asked questions
How is ValueError different from TypeError?
TypeError is about the wrong kind of value, ValueError is about a wrong value of the right kind.
Why does int("ten") fail?
int() reads only digits with an optional sign and surrounding spaces. Number words are not converted.