How to Resolve Python TypeError: "unsupported operand type(s)"
The TypeError: unsupported operand type(s) is a frequent error in Python. It signals that you've attempted to use an operator (like +, -, *, /) with data types that don't support that specific operation together.
This guide explains the common causes for this error with different type combinations and provides clear solutions.
Understanding "Unsupported Operand Type(s)"
This TypeError fundamentally means you're trying to perform an operation that isn't defined for the combination of data types you're using. For example, you can add two numbers (1 + 2), and you can concatenate two strings ('a' + 'b'), but you can not directly add a number and a string (1 + 'a').
Error: +: int and str
- Cause: Using the addition operator (
+) between an integer and a string. Python doesn't know whether you intend mathematical addition or string concatenation. - Error Example:
my_int = 10my_str = '5'try:# ⛔️ TypeError: unsupported operand type(s) for +: 'int' and 'str'result = my_int + my_strexcept TypeError as e:print(e)
- Solutions:
- Convert string to number (for addition): Use
int()orfloat().result_add = my_int + int(my_str)print(f"Addition: {result_add}") # Output: Addition: 15 - Convert number to string (for concatenation): Use
str().result_concat = str(my_int) + my_strprint(f"Concatenation: {result_concat}") # Output: Concatenation: 105 - Use F-strings (for embedding in strings): F-strings handle conversion automatically.
result_fstring = f"Value: {my_int}{my_str}"print(f"F-string: {result_fstring}") # Output: f-string: Value: 105
- Convert string to number (for addition): Use
- Note: The
input()function always returns a string. Convert its result usingint()orfloat()if numeric operations are needed.
Error: -: str and str
- Cause: Using the subtraction operator (
-) with two strings. Subtraction is not defined for strings. - Error Example:
str_1 = '50'str_2 = '20'try:# ⛔️ TypeError: unsupported operand type(s) for -: 'str' and 'str'result = str_1 - str_2except TypeError as e:print(e)
- Solution: Convert both strings to numbers (
intorfloat) before subtracting.result = int(str_1) - int(str_2)print(result) # Output: 30
Error: -: int and function
- Cause: Attempting to subtract a function object itself (instead of its return value) from an integer.
- Error Example:
def get_num():return 25try:# ⛔️ TypeError: unsupported operand type(s) for -: 'int' and 'function'result = 50 - get_num # Forgot parentheses ()except TypeError as e:print(e)
- Solution: Call the function using parentheses
()to get its return value before performing the subtraction.result = 50 - get_num() # Call the functionprint(result) # Output: 25 - Ensure the function actually returns a numeric value compatible with subtraction.
Error: /: list and int
- Cause: Trying to use the division operator (
/) between a list object and an integer. Division isn't defined for lists. - Error Example:
my_list = [10, 20, 30]my_int = 5try:# ⛔️ TypeError: unsupported operand type(s) for /: 'list' and 'int'result = my_list / my_intexcept TypeError as e:print(e)
- Solutions:
- Divide a specific element: Access an element by index.
result = my_list[0] / my_intprint(result) # Output: 2.0
- Divide each element: Use a loop or list comprehension.
new_list = [num / my_int for num in my_list]print(new_list) # Output: [2.0, 4.0, 6.0]
- Divide the sum: Use
sum().result = sum(my_list) / my_intprint(result) # Output: 12.0
- Divide a specific element: Access an element by index.
Error: /: tuple and int
- Cause: Similar to lists, trying to use the division operator (
/) between a tuple object and an integer. - Error Example:
my_tuple = (10, 20, 30) # Or my_tuple = 10, 20, 30my_int = 2try:# ⛔️ TypeError: unsupported operand type(s) for /: 'tuple' and 'int'result = my_tuple / my_intexcept TypeError as e:print(e)
- Solutions: The solutions are analogous to lists (access element, iterate, sum).
- Divide a specific element:
result = my_tuple[0] / my_intprint(result) # Output: 5.0
- Divide each element:
new_list = [x / my_int for x in my_tuple]new_tuple = tuple(new_list)print(new_tuple) # Output: (5.0, 10.0, 15.0)
- Divide the sum:
result = sum(my_tuple) / my_intprint(result) # Output: 30.0
- Divide a specific element:
Error: /: str and int
- Cause: Trying to use the division operator (
/) between a string and an integer. - Error Example:
my_str = '10'my_num = 5try:# ⛔️ TypeError: unsupported operand type(s) for /: 'str' and 'int'result = my_str / my_numexcept TypeError as e:print(e)
- Solution: Convert the string to a number (
intorfloat) before dividing.result = int(my_str) / my_numprint(result) # Output: 2.0 - Use
//for floor division if an integer result is desired (after conversion).
Error: *: float and decimal.Decimal
- Cause: Using arithmetic operators between standard Python floats and
decimal.Decimalobjects. These types have different internal representations and precision rules, making direct operations ambiguous. - Error Example:
from decimal import Decimalmy_float = 3.2my_decimal = Decimal('3.14')try:# ⛔️ TypeError: unsupported operand type(s) for *: 'float' and 'decimal.Decimal'result = my_float * my_decimalexcept TypeError as e:print(e)
- Solution: Convert one type to match the other. Converting the
floattoDecimalis generally preferred for maintaining precision.from decimal import Decimalmy_float = 3.2my_decimal = Decimal('3.14')# Convert float to Decimalresult = Decimal(my_float) * my_decimalprint(result) # Output: 10.04800000000000055777604757# Or convert Decimal to float (potential precision loss)# result = my_float * float(my_decimal)# print(result) # Output: 10.048
General Debugging: Checking Variable Types
If you encounter an "unsupported operand type(s)" error and aren't sure why, check the types of your variables using type() or isinstance():
my_var1 = 10
my_var2 = "5"
print(f"my_var1: value={my_var1}, type={type(my_var1)}")
print(f"my_var2: value={my_var2}, type={type(my_var2)}")
print(f"Is my_var1 an int? {isinstance(my_var1, int)}")
print(f"Is my_var2 a str? {isinstance(my_var2, str)}")
This helps identify the incompatible types involved in the operation.
Conclusion
The TypeError: unsupported operand type(s) error highlights the importance of understanding data types and operator compatibility in Python.
- The solution usually involves converting one or both operands to compatible types (often using
int(),float(),str(), orDecimal()) or ensuring you are operating on the intended data (e.g., calling a function instead of using the function object itself, or accessing elements within a list/tuple). - Checking variable types can be a valuable debugging step.