ValueError
This error occurs when a function receives an argument of the correct data type but with an invalid value (e.g. parsing an alphanumeric string as an integer).
Usually happens because:
- ☑ Passing invalid text strings to type conversion constructors
- ☑ Mismatch between variable count and unpacked items size
- ☑ Searching or removing missing items from collections
🔍 Quick Checklist:
What is ValueError?
A 'ValueError' is raised at runtime when a built-in operation or function receives an argument that has the correct data type but contains an inappropriate value. For example, the 'int()' constructor accepts string inputs, but calling 'int("xyz")' raises a ValueError because the string cannot be parsed as a base-10 numerical digit. It is also commonly raised during list unpacking operations when the number of target variables does not match the items count in the iterable.
Common Causes
- Invalid type conversion value: Passing an incompatible value to parsing constructors (e.g. 'int("abc")' or 'float("nan")' in invalid contexts).
- Mismatched tuple/list unpacking: Trying to unpack an iterable into too many or too few variables.
- Invalid value search query: Running '.index()' or '.remove()' on a list or string for an item that does not exist.
| Cause | Frequency |
|---|---|
| Alphanumeric string parsing in int() constructor | ⭐⭐⭐⭐⭐ |
| Mismatched iterable variables unpacking count | ⭐⭐⭐⭐ |
| Searching non-existent items in list index() | ⭐⭐⭐ |
Common Mistakes
- Running list `.remove()` or `.index()` on user inputs directly without checking if the value exists in the list, which will raise a ValueError when missing.
- Unpacking values returned by database query cursors (e.g. `x, y = query()`) assuming 2 items are always returned, causing crashes when queries yield empty lists or single rows.
How to Fix
Python Operations & Verification
Wrap casting attempts inside try/except structures to return fallback values on parse failures.
def parse_port(port_str):
try:
return int(port_str)
except ValueError:
print(f"Warning: '{port_str}' is not a valid port. Defaulting to 8080.")
return 8080Platform Specific Fixes
Test input numeric validations in interactive python shell prompts.
python3 -c "text = '123'; print(text.isdigit())"Best Practices
- Use target collection checks (`if item in list:`) to safeguard index search methods.
- Validate input formats using standard patterns before executing operations.
Frequently Asked Questions (FAQ)
Q: What is the difference between TypeError and ValueError?
TypeError is raised when you pass a completely wrong type (e.g. passing a list to int()). ValueError is raised when the type is correct, but the value is invalid (e.g. passing 'abc' to int()).
Q: How do I fix 'ValueError: not enough values to unpack'?
This means you are trying to unpack an iterable (like a list) into more variables than it contains (e.g. 'a, b, c = [1, 2]'). Ensure the number of variables matches the list size, or use 'a, *b = [1, 2, 3]' to capture remaining items.
Q: How do I safely parse an integer in Python?
Use a try/except block: 'try: val = int(text) except ValueError: val = 0'.
Q: Why does list.remove() throw a ValueError?
If you run 'my_list.remove("item")' but "item" is not in the list, Python raises a ValueError. Always check if the item is present using 'if "item" in my_list:' first.