TypeError: unsupported operand type(s)

Loading

The error message:

TypeError: unsupported operand type(s) for X: 'type1' and 'type2'

occurs when you try to perform an operation between incompatible data types.


1. Causes and Solutions

Cause 1: Adding a String and an Integer

If you try to add a number (int) and a string (str), Python does not know how to handle it.

Incorrect Code:

age = 25
message = "My age is: " + age # Cannot add str and int

Error Output:

TypeError: can only concatenate str (not "int") to str

Solution: Convert int to str Before Concatenation

message = "My age is: " + str(age)  # Correct way
print(message)

Cause 2: Using the Wrong Operator Between Lists, Integers, or Strings

Some operators are not supported between certain types.

Incorrect Code:

result = [1, 2, 3] - [1, 2]  # Cannot subtract lists

Error Output:

TypeError: unsupported operand type(s) for -: 'list' and 'list'

Solution: Use set to Subtract Lists

result = list(set([1, 2, 3]) - set([1, 2]))  # Returns [3]

Cause 3: Multiplying a List by a Float

Multiplication works between a list and an integer, but not with a float.

Incorrect Code:

nums = [1, 2, 3]
result = nums * 2.5 # Cannot multiply list by float

Error Output:

TypeError: can't multiply sequence by non-int of type 'float'

Solution: Use an Integer

result = nums * 2  # Works fine
print(result) # Output: [1, 2, 3, 1, 2, 3]

Cause 4: Using None in Arithmetic Operations

If a variable is None, you cannot use it in calculations.

Incorrect Code:

x = None
print(x + 5) # Cannot add None and int

Error Output:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Solution: Assign a Proper Value

x = 0  # Set a valid number
print(x + 5) # Works fine

Cause 5: Incorrect Use of Division (/ vs //)

Python 3 uses floating-point division (/) by default, but integer division (//) works differently.

Incorrect Code:

result = "100" / 5  # Cannot divide string by number

Error Output:

TypeError: unsupported operand type(s) for /: 'str' and 'int'

Solution: Convert the String to an Integer

result = int("100") / 5  # Works fine

Leave a Reply

Your email address will not be published. Required fields are marked *