How to Resolve Python "TypeError: '<' / '>' not supported between instances of X and Y"
The TypeError: '<' not supported between instances of 'X' and 'Y'
(or the same error with >
) is a common runtime error in Python. It signals that you attempted to use a comparison operator (<
, >
, <=
, >=
) between two objects of types 'X' and 'Y' for which Python does not define a natural ordering or comparison method. This often happens when comparing numbers with strings, lists with numbers, functions/methods with numbers, etc.
This guide explains the cause of this error and provides solutions by ensuring comparable types or using appropriate alternative operations.
Understanding the Error: Type Compatibility in Comparisons
Python's comparison operators (<
, >
, <=
, >=
) work by comparing the values of two objects. This comparison is only meaningful and defined if the objects are of compatible types for which an order relationship makes sense.
- You can compare numbers (
int
,float
):5 < 10.5
isTrue
. - You can compare strings lexicographically:
'apple' < 'banana'
isTrue
. - You can compare lists/tuples element by element (lexicographically):
[1, 2] < [1, 3]
isTrue
.
However, Python generally does not define an ordering between fundamentally different, incompatible types like strings and numbers, or lists and numbers. Trying to compare them directly results in the TypeError
.
Scenario 1: Comparing Strings and Numbers (str
and int
/float
)
Error Message: TypeError: '<' not supported between instances of 'str' and 'int'
(or float
)
Cause: Direct Comparison
You used <
, >
, <=
, or >=
between a string variable and an integer or float variable.
age_string = "30" # String
age_limit = 21 # Integer
# Error Scenario
try:
# ⛔️ TypeError: '>' not supported between instances of 'str' and 'int'
is_older = age_string > age_limit
print(is_older)
except TypeError as e:
print(e)
Python doesn't know if the string "30"
is inherently "greater than" the integer 21
.
Solution: Convert String to Number (int()
, float()
)
If the string represents a number, convert it to the appropriate numeric type (int
or float
) before the comparison.
age_string = "30"
age_limit = 21
# ✅ Convert string to integer before comparing
age_as_int = int(age_string)
is_older = age_as_int > age_limit
print(f"Comparing int({age_string}) > {age_limit}: {is_older}") # Output: True
# Example with float
price_string = "19.99"
budget = 20.0
price_as_float = float(price_string)
can_afford = price_as_float <= budget
print(f"Comparing float({price_string}) <= {budget}: {can_afford}") # Output: True
int()
or float()
will raise a ValueError
if the string cannot be converted (e.g., int('hello')
). Use try...except ValueError
if the string might not be a valid number.
Note on User Input
Remember input()
always returns a string. Convert user input intended for numerical comparison using int()
or float()
.
user_input = input("Enter your score: ") # User types '85'
score_string = user_input # score_string is '85'
passing_score = 70
try:
# ✅ Convert input string to integer
score_int = int(score_string)
if score_int >= passing_score:
print("You passed!") # This is executed
else:
print("You did not pass.")
except ValueError:
print("Invalid score entered. Please enter a number.")
Output:
Enter your score: 85
You passed!
Note on min()
and max()
Passing a mix of strings and numbers to min()
or max()
(when called with multiple arguments or an iterable containing mixed types) will also cause this TypeError
because these functions rely on comparisons. Convert all items to a comparable type first.
mixed_data = [50, "100", 25, "75"]
# Error Scenario
try:
# ⛔️ TypeError: '>' not supported between instances of 'str' and 'int'
maximum = max(mixed_data)
print(maximum)
except TypeError as e:
print(f"Error with max() on mixed types: {e}")
# Solution: Convert all to a consistent numeric type
numeric_data = [int(x) for x in mixed_data] # Assumes all strings are valid ints
maximum = max(numeric_data)
minimum = min(numeric_data)
print(f"Converted data: {numeric_data}")
print(f"Max: {maximum}, Min: {minimum}") # Output: Max: 100, Min: 25
Output:
Error with max() on mixed types: '>' not supported between instances of 'str' and 'int'
Converted data: [50, 100, 25, 75]
Max: 100, Min: 25
Scenario 2: Comparing Sequences and Numbers (list
/tuple
and int
/float
)
Error Message: TypeError: '<' not supported between instances of 'list' and 'int'
(or tuple
)
Cause: Direct Comparison
You tried to compare a list or tuple object directly to a number.
my_list = [10, 20, 30]
threshold = 25
# Error Scenario
try:
# ⛔️ TypeError: '<' not supported between instances of 'list' and 'int'
is_list_less = my_list < threshold
print(is_list_less)
except TypeError as e:
print(e)
Python doesn't define a less-than/greater-than relationship between a sequence object and a number.
Solution: Compare an Element or the Length
Your intention was likely different:
- Compare an element: Access a specific element within the list/tuple and compare that element to the number.
my_list = [10, 20, 30]
threshold = 25
# ✅ Compare the first element
is_first_less = my_list[0] < threshold
print(f"Is first element ({my_list[0]}) < {threshold}? {is_first_less}")
# Output: Is first element (10) < 25? True - Compare the length: Use the
len()
function to get the number of items and compare that integer to the other number.my_list = [10, 20, 30]
max_length = 5
# ✅ Compare the list's length
is_short_enough = len(my_list) <= max_length
print(f"Is length ({len(my_list)}) <= {max_length}? {is_short_enough}")
# Output: Is length (3) <= 5? True - Check if all elements meet a condition: Use
all()
with a generator expression.my_list = [10, 20, 30]
limit = 40
all_below_limit = all(item < limit for item in my_list)
print(f"Are all items < {limit}? {all_below_limit}")
# Output: Are all items < 40? True - Check if any element meets a condition: Use
any()
with a generator expression.my_list = [10, 20, 30]
threshold = 25
any_above_threshold = any(item > threshold for item in my_list)
print(f"Is any item > {threshold}? {any_above_threshold}")
# Output: Is any item > 25? True
Scenario 3: Comparing Functions/Methods and Numbers (function
/method
and int
/float
)
Error Message: TypeError: '>' not supported between instances of 'function' and 'int'
(or method
)
Cause: Forgetting Call Parentheses ()
You compared the function or method object itself to a number, instead of calling the function/method first and comparing its return value.
def get_count():
return 50
limit = 100
# Error Scenario
try:
# ⛔ ️ TypeError: '>' not supported between instances of 'function' and 'int'
# Comparing the function object, not its return value
is_over_limit = get_count > limit
print(is_over_limit)
except TypeError as e:
print(e)
Output:
'>' not supported between instances of 'function' and 'int'
Solution: Call the Function/Method Before Comparing
Add parentheses ()
after the function/method name to execute it and get its return value, then compare the return value.
def get_count():
return 50
limit = 100
# ✅ Call the function first, then compare its return value
count_value = get_count() # count_value is 50
is_over_limit = count_value > limit
print(f"Comparing {count_value} > {limit}: {is_over_limit}")
# Can be done directly in the comparison:
is_over_limit_direct = get_count() > limit
print(f"Comparing get_count() > {limit}: {is_over_limit_direct}")
Output:
Comparing 50 > 100: False
Comparing get_count() > 100: False
General Solution: Ensure Compatible Types
The fundamental solution for all these TypeError
variations is to ensure that the two operands involved in the comparison (<
, >
, <=
, >=
) are of compatible types for which Python defines an order relationship (usually number-number, string-string, list-list, tuple-tuple). Perform necessary conversions (int()
, float()
, str()
) or access the correct value (list element, function return value, len()
) before attempting the comparison.
Debugging: Check Variable Types (type()
, isinstance()
)
If you're unsure about the types involved, print them before the comparison:
value1 = "10"
value2 = 5
print(f"Type of value1: {type(value1)}") # <class 'str'>
print(f"Type of value2: {type(value2)}") # <class 'int'>
try:
result = value1 < value2
except TypeError as e:
print(f"Caught error: {e}") # Shows the incompatible types
Output:
ERROR!
Type of value1: <class 'str'>
Type of value2: <class 'int'>
Caught error: '<' not supported between instances of 'str' and 'int'
Conclusion
The TypeError: '<'/' >' not supported between instances of 'X' and 'Y'
occurs when you try to compare incompatible types using <
, >
, <=
, or >=
.
To fix it:
- If comparing strings and numbers, convert the string to
int()
orfloat()
first. - If comparing lists/tuples and numbers, compare a specific element (
my_list[index]
) or the length (len(my_list)
) to the number, or useany()
/all()
for element-wise checks. - If comparing functions/methods and numbers, call the function/method first using
()
to get its return value, then compare the return value.
Always ensure the operands in a comparison are of types that Python knows how to order relative to each other.