Нужно написать функцию которая принимает в себя элементы списка в качестве аргумента и возвращает его с элементами число которых не превышает 20
Если делать без функции тобиш так:
j=[2,4,16,32,64]
j2 = [i for i in j if i < 21]
print(j2)
То это все работает
Но если через функцию:
def function(*array):
finaly_array = [i for i in array if i < 21]
return finaly_array
function([2,4,6,8,10,20,22,40,142])
То выбивает ошибку: TypeError: '<' not supported between instances of 'list' and 'int'
To fix the “TypeError: < not supported between instances of list and int” error in Python, there are some solutions we have effectively tested. Follow the article to better understand.
What causes the “TypeError: < not supported between instances of list and int” error?
In Python, the ‘<‘ operator which means less than. The ‘<‘ operator operates between two operands and checks if the left operand is less than the right operand. If less, It returns True and False if the condition is not satisfied.
TypeError: Python throws this error when you perform an unsupported operation on an object with an invalid data type.
The error “TypeError: < not supported between instances of list and int” happens when you use the ‘<‘ operator to compare two values that are not of the same data type.
Example:
# Creat a list of students' marks students = ["Tom", "Perter", "Jery"] marks = [4, 10, 5] avgMark = 5 for i in range(len(marks)): # TypeError: '<' not supported between instances of 'list' and 'int' if marks < avgMark: print(f"{students[i]}: Failed") else: print(f"{students[i]}: Passed")
Output:
Traceback (most recent call last):
File "code.py", line 8, in <module>
if marks < avgMark:
TypeError: '<' not supported between instances of 'list' and 'int'
How to solve this error?
Access each index of the list
To solve this error, please access each list index, and call each element out using the ‘<‘ operator to compare with integers. Replace the code if marks < avgMark
with the code if marks[i] < avgMark
This ensures you will not have any errors.
# Create a list of students' marks students = ["Tom", "Perter", "Jery"] marks = [4, 10, 5] avgMark = 5 for i in range(len(marks)): if marks[i] < avgMark: print(f"{students[i]}: Failed") else: print(f"{students[i]}: Passed")
Output:
Tom: Failed
Perter: Passed
Jery: Passed
Using the list comprehension
marks = [4, 10, 5] avgMark = 5 # Use the list comprehension marksPassed = [m for m in marks if m >= avgMark] print(marksPassed) print("Number of students who have passed: ", len(marksPassed))
Output:
[10, 5]
Number of students who have passed: 2
Summary
If you have any questions about the error “TypeError: < not supported between instances of list and int” in Python, please leave a comment below. We will support your questions. Thank you for reading!
Maybe you are interested:
- TypeError: Object of type DataFrame is not JSON serializable in Python
- TypeError: string argument without an encoding in Python
- TypeError: unsupported operand type(s) for -: str and int
- TypeError: ‘<‘ not supported between instances of ‘NoneType’ and ‘int’
My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.
Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java
Have you experienced Typeerror not supported between instances of list and int?
This error is common when you are working on your Python project. This error is quite frustrating but unmistakably, a solution exists.
This error can be fixed in several ways, particularly:
- Check the types of your variables
- Convert the list to an integer
- Convert the integer to a list
- Use list comprehension
But before we resolve this Typeerror not supported between instances of list and int error, let’s understand first what and how this error occurs.
“TypeError: not supported between instances of list and int” is an error message that occurs in Python when you try to perform an operation that is not supported between a list and an integer.
In other words, you are trying to apply an operation, such as addition or subtraction, between a list and an integer. Since these two types are not compatible, Python throws an error.
For example, let’s say you have a list called my_list and an integer called my_num, and you try to compare operators between values of incompatible types like this:
my_list = [1, 2, 3]
my_num = 4
result = my_list + my_num
This would result in the “TypeError: not supported between instances of list and int” error because you are trying to compare a list and an integer together, which is not a valid operation in Python.
How to solve Typeerror not supported between instances of list and int
1. Check the types of your variables
Make sure that you are not accidentally trying to perform an operation between a list and an integer.
Check the types of your variables using the type() function and adjust your code accordingly.
2. Convert the list to an integer
If you need to perform a mathematical operation between a list and an integer, you can convert the list to an integer using functions like sum(), min(), or max().
For example:
my_list = [10, 20, 30]
my_num = 40
result = sum(my_list) + my_num
print(result)
In this case, the sum() function will add up all the elements in the list, returning an integer that can be added to my_num.
Output:
100
3. Convert the integer to a list
If you need to combine a list and an integer into a new list, you can convert the integer to a list using the list() function and then concatenate the two lists using the + operator.
- For example:
my_list = [10, 20, 30]
my_num = 40
new_list = my_list + list(str(my_num))
print(new_list)
In this case, we convert my_num to a string using the str() function, then to a list using the list() function, and finally concatenate it with my_list.
Output:
[10, 20, 30, '4', '0']
4. Use list comprehension
If you need to perform a specific operation on each element of the list and then combine the results with an integer, you can use list comprehension.
For example:
my_list = [10, 20, 30]
my_num = 40
new_list = [num * my_num for num in my_list]
print(new_list)
In this case, we multiply each element in my_list by my_num using list comprehension, resulting in a new list of integers.
Output:
[400, 800, 1200]
These are just a few possible solutions to the “TypeError: not supported between instances of list and int” error. The best solution will depend on your specific use case and what you are trying to achieve in your code.
Conclusion
In conclusion, “TypeError: not supported between instances of list and int” can be solved by following the outlined solution above.
Remember that this error occurs when you try to perform an operation that is not supported between a list and an integer.
Anyhow, If you are finding solutions to some errors you might encounter we also have Typeerror: can’t compare offset-naive and offset-aware datetimes.
tf version: 2.4.0
vocab = ["a", "b", "c", "d"]
table = tf.keras.layers.experimental.preprocessing.StringLookup(vocab)
TypeError Traceback (most recent call last)
in
—-> 1 table = tf.keras.layers.experimental.preprocessing.StringLookup(vocab)/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/layers/preprocessing/string_lookup.py in init(self, max_tokens, num_oov_indices, mask_token, oov_token, vocabulary, encoding, invert, **kwargs)
197 vocabulary=vocabulary,
198 invert=invert,
—> 199 **kwargs)
200 base_preprocessing_layer._kpl_gauge.get_cell(«V2»).set(«StringLookup»)
201/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/layers/preprocessing/index_lookup.py in init(self, max_tokens, num_oov_indices, mask_token, oov_token, vocabulary, invert, **kwargs)
92 # If max_tokens is set, the value must be greater than 1 — otherwise we
93 # are creating a 0-element vocab, which doesn’t make sense.
—> 94 if max_tokens is not None and max_tokens <= 1:
95 raise ValueError(«If set,max_tokens
must be greater than 1.»)
96TypeError: ‘<=’ not supported between instances of ‘list’ and ‘int’
Loyvsc 6 / 6 / 1 Регистрация: 19.05.2020 Сообщений: 212 |
||||
1 |
||||
17.10.2021, 08:41. Показов 2340. Ответов 4 Метки нет (Все метки)
Здравствуйте. В этом коде, выдаёт эту ошибку — ‘<‘ not supported between instances of ‘list’ and ‘int’ (по 10-ой строке)
0 |
Автоматизируй это! 7110 / 4408 / 1182 Регистрация: 30.03.2015 Сообщений: 12,859 Записей в блоге: 29 |
|
17.10.2021, 08:53 |
2 |
Loyvsc, почему не попробовал перевести и подумать? нельзя сравнить список с числом. Зачем ты их сравниваешь?
0 |
Viktorrus 1728 / 967 / 199 Регистрация: 22.02.2018 Сообщений: 2,694 Записей в блоге: 6 |
||||
17.10.2021, 09:12 |
3 |
|||
Loyvsc, Вы понимаете как выглядит матрица в питоне?
Элементами матрицы A являются списки. А списки нельзя сравнивать с числом. Поэтому и выдается сообщение об ошибке.
0 |
6 / 6 / 1 Регистрация: 19.05.2020 Сообщений: 212 |
|
17.10.2021, 13:54 [ТС] |
4 |
Я сравниваю элемент списка: A[i]. Добавлено через 44 секунды
0 |
enx 1182 / 758 / 277 Регистрация: 05.09.2021 Сообщений: 1,772 |
||||
17.10.2021, 14:05 |
5 |
|||
РешениеLoyvsc, ………….что писать на место нулей, сам думай.
1 |