What does TypeError: unsupported operand type(s) mean in Python?
What causes this error
This TypeError occurs when an operator or built-in function receives an object of an inappropriate type. For example, '5' + 5 raises it because you can't add a string and an integer. Similarly, 'abc' * 'def' fails because you can't multiply two strings.
The error message usually specifies the operator and the types involved, like "unsupported operand type(s) for +: 'int' and 'str'". This tells you exactly which types are incompatible.
How to fix it
Check the types of the operands using type() or isinstance(). Then convert one or both to a compatible type. For example, if you have an integer and a string, convert the string to an integer with int() or the integer to a string with str(), depending on what you want to achieve.
If you're working with user input, remember that input() always returns a string. Convert it to the desired type before doing math. If you're combining numbers and strings for output, use f-strings or .format() to avoid manual conversion.
- Use type() to inspect the types of your variables.
- Convert strings to numbers with int() or float() before arithmetic.
- Convert numbers to strings with str() when concatenating.
- Use f-strings (e.g., f"{num} apples") for mixing types in output.
- Check for None values, which also cause this error with most operators.
Examples and edge cases
If you have age = input("Age: ") and then next_year = age + 1, you'll get this error because age is a string. Fix it with age = int(input("Age: ")). If you have a list and an integer, like [1,2] + 3, you'll get it too; use [1,2] + [3] or [1,2].append(3).
Custom classes can also raise this if they don't implement the necessary special methods (like __add__). If you're defining your own types, implement the appropriate dunder methods to support operators.
Common mistakes
- Forgetting that input() returns a string, leading to type errors in arithmetic.
- Assuming Python will automatically convert types like some other languages do.
- Ignoring None values, which often cause this error when used with operators.
