TypeError: < not supported between instances of list and int

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Nellia Kurme

TypeError: < not supported between instances of list and int #

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.

typeerror not supported between instances of list and int

Here is an example of how the error occurs.

main.py
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.

To solve the error, make sure the values you are comparing are of compatible types.

One way to solve the error is to access a specific item in the list.

main.py
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.

The values you are comparing have to be of compatible types. If the list contains numbers wrapped in a string, convert the string to a number using the int() or float() classes.

If you meant to filter out integers in a list based on a comparison, use a list comprehension.

main.py
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.

main.py
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.

main.py
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.

The values on the left-hand and right-hand sides of the comparison operator need to be of compatible types.

If you aren't sure what type of object a variable stores, use the built-in type() class.

main.py
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.

Use the search field on my Home Page to filter through my more than 1,000 articles.