Encountering a TypeError: not supported between instances of 'str' and 'int' is a common frustration for Python developers, especially when they are just starting to work with data comparisons or sorting operations. This error message tells you that the interpreter tried to use a comparison operator (like <, >, <=, >=, ==, or !=) on a string and an integer, which Python does not allow because the two types have no defined ordering relationship. Understanding why this happens, where it typically appears, and how to resolve it will save you debugging time and help you write more strong code The details matter here..
Understanding the Error
At its core, Python is a strongly typed language when it comes to operations that require a clear meaning. While Python will happily convert between numeric types (e.Practically speaking, g. , adding an int to a float), it refuses to compare a string with an integer because there is no universal rule that says whether "5" is greater than, less than, or equal to 5. The interpreter therefore raises a TypeError to alert you that the operation is ambiguous.
The exact traceback usually looks like this:
TypeError: '<' not supported between instances of 'str' and 'int'
or, depending on the operator used:
TypeError: '>' not supported between instances of 'str' and 'int'
The message varies with the operator, but the root cause is identical: you attempted to compare incompatible types Nothing fancy..
Common Scenarios That Trigger the Error
1. User Input Compared to Numbers
When you collect input from the console using input(), Python returns a string. If you forget to convert that string to a numeric type before comparing it to a number, the error appears.
age = input("Enter your age: ") # age is a string, e.g., "25"
if age > 18: # TypeError: '>' not supported between str and int
print("You are an adult")
2. Mixed Data in Lists or Arrays
Sorting a list that contains both strings and integers triggers the error because the sorting algorithm needs to compare elements pairwise.
mixed = [5, "apple", 3, "banana"]
mixed.sort() # TypeError: '<' not supported between instances of 'str' and 'int'
3. Dictionary Keys or Values with Inconsistent Types
If you attempt to compare dictionary values that are not uniformly typed, you may hit the same problem Most people skip this — try not to..
data = {"score": "90", "level": 2}
if data["score"] > data["level"]: # Comparing string "90" with int 2
print("High score")
4. Reading from Files or CSV Without Proper Parsing
When you read lines from a text file or CSV, each field is initially a string. Forgetting to cast numeric columns leads to comparison errors later in the code.
with open("data.csv") as f:
for line in f:
parts = line.strip().split(",")
value = parts[1] # still a string
if value > 100: # TypeError
...
5. Using Comparison Operators in Custom Classes Without Proper __lt__, __gt__, etc.
If you define a class that stores both string and integer attributes and then try to compare instances directly, Python falls back to comparing the attributes, which may cause the error if they are mismatched Easy to understand, harder to ignore..
class Item:
def __init__(self, name, quantity):
self.name = name # str
self.quantity = quantity # int
a = Item("widget", 5)
b = Item("gadget", "three") # quantity mistakenly a string
if a < b: # tries to compare 5 < "three"
...
How to Diagnose the Problem
-
Read the Traceback Carefully
The line number and the operator shown (<,>,==, etc.) point directly to the problematic comparison Small thing, real impact.. -
Inspect the Types Involved
Add a quickprint(type(variable))or useisinstance()before the comparison to confirm what you are dealing with Took long enough..print(type(age), type(18)) # -
Look for Recent Changes
If the error appeared after editing a specific function or after integrating new data, focus on the variables that were modified. -
Use a Debugger or Interactive Shell
Tools likepdbor Jupyter notebooks let you pause execution and examine the state of each variable at the moment of failure.
Strategies to Fix the Error
Explicit Type Conversion
The most straightforward fix is to convert the offending operand to the expected type before the comparison.
age = int(input("Enter your age: ")) # Convert string to int
if age > 18:
print("You are an adult")
Be cautious: if the string might not represent a valid integer, wrap the conversion in a try/except block to handle ValueError.
try:
age = int(input("Enter your age: "))
except ValueError:
print("Please enter a valid number.")
age = 0
Homogenize Data Structures
When working with collections, ensure all elements share a compatible type before sorting or comparing The details matter here. Surprisingly effective..
mixed = [5, "apple", 3, "banana"]
# Convert everything to strings (or to a comparable numeric representation)
str_list = [str(x) for x in mixed]
str_list.sort()
print(str_list) # ['3', '5', 'apple', 'banana']
If you need to keep the original types, consider separating them into different lists or using a tuple with a sort key Most people skip this — try not to..
mixed = [5, "apple", 3, "banana"]
# Sort by type name, then value
mixed.sort(key=lambda x: (type(x).__name__, x))
print(mixed) # [3, 5, 'apple', 'banana']
Use Comparison Functions That Handle Type Differences
Python’s functools.total_ordering or the operator module can help when you need custom comparison logic.
from functools import total_ordering
@total_ordering
class MixedItem:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return str(self.value) == str(other.value)
def __lt__(self, other):
return str(self.value) < str(other.value)
# Now you can compare MixedItem instances regardless of original type
a = MixedItem(5