Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Fineas Anton
The Python "TypeError: '>' not supported between instances of 'tuple' and
'int'" occurs when we use a comparison operator between values of type tuple
and int
. To solve the error, access the tuple at a specific index or compare
the tuple's length to an integer.
Here is an example of how the error occurs.
my_tuple = 2, 4, 6 my_int = 5 # ⛔️ TypeError: '>' not supported between instances of 'tuple' and 'int' print(my_tuple > my_int)
We used a comparison operator between values of incompatible types (tuple and int) which caused the error.
One way to solve the error is to access a specific item in the tuple.
my_tuple = 2, 4, 6 my_int = 5 print(my_tuple[0] > my_int) # 👉️ False
We accessed the tuple item at index 0
(the first item) and compared it to an
integer.
int()
or float()
classes.If you meant to filter out integers in a tuple based on a comparison, use a list comprehension.
my_tuple = 2, 4, 6, 8 my_int = 5 new_tuple = tuple([x for x in my_tuple if x > my_int]) print(new_tuple) # 👉️ (6, 8)
The example shows how to filter out all values in the tuple that are not greater
than 5
.
If you meant to compare the tuple's length to an integer, use the len()
function.
my_tuple = 2, 4, 6, 8 my_int = 5 print(len(my_tuple) > my_int) # 👉️ False print(len(my_tuple)) # 👉️ 4
The len() function returns the length (the number of items) of an object.
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).
In case you declared a tuple by mistake, tuples are constructed in multiple ways:
()
creates an empty tuplea,
or (a,)
a, b
or (a, b)
tuple()
constructorIf you meant to compare the sum of the items in the tuple to an integer, use the
sum()
function.
my_tuple = 2, 4, 6, 8 my_int = 5 print(sum(my_tuple) > my_int) # 👉️ True print(sum(my_tuple)) # 👉️ 20
The sum function takes an iterable, sums its items from left to right and returns the total.
If you aren't sure what type of object a variable stores, use the built-in
type()
class.
my_tuple = 2, 4, 6, 8 print(type(my_tuple)) # 👉️ <class 'tuple'> print(isinstance(my_tuple, tuple)) # 👉️ True my_int = 5 print(type(my_int)) # 👉️ <class 'int'> print(isinstance(my_int, int)) # 👉️ True
The type class returns the type of an object.
The isinstance
function returns True
if the passed in object is an instance or a subclass of
the passed in class.