Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Nellia Kurme
The Python "TypeError: '<' not supported between instances of 'list' and
'int'" occurs when we use a comparison operator between values of type list
and int
. To solve the error, access the list at a specific index or compare
the list's length to an integer.
Here is an example of how the error occurs.
my_list = [3, 5, 8] my_int = 10 # ⛔️ TypeError: '<' not supported between instances of 'list' and 'int' print(my_list < my_int)
We used a comparison operator between values of incompatible types (list and int) which caused the error.
One way to solve the error is to access a specific item in the list.
my_list = [3, 5, 8] my_int = 10 print(my_list[0] < my_int) # 👉️ True
We accessed the list 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 list based on a comparison, use a list comprehension.
my_list = [3, 5, 8, 10, 15] new_list = [x for x in my_list if x > 7] print(new_list) # 👉️ [8, 10, 15]
The example shows how to filter out all values in the list that are not greater
than 7
.
If you meant to compare the list's length to an integer, use the len()
function.
my_list = [3, 5, 8] my_int = 10 print(len(my_list) > my_int) # 👉️ False print(len(my_list)) # 👉️ 3
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).
If you meant to compare the sum of the items in the list to an integer, use the
sum()
function.
my_list = [3, 5, 8] my_int = 10 print(sum(my_list) > my_int) # 👉️ True print(sum(my_list)) # 👉️ 16
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_list = [3, 5, 8] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ True my_int = 10 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.