. Advertisement .
..3..
. Advertisement .
..4..
When working on a Python program or a beginner trying to design a program, getting TypeError in return is quite common. You may encounter various TypeErrors. Today we discuss TypesError unsupported operand type(s) for /: list and int. This error warning comes when you are working with a list and integer. Take a look at how to fix this error
How to Fix TypesError unsupported operand type(s) for /: list and int
The TypesError unsupported operand type(s) for /: list and int occurs when you are trying to divide or use the division operator ‘/’ with a number and a list. Once you correct how a list has assigned variables and accurately use the operator, you can use the program without any TypeError.
Have a look at the examples and methods
Check How the Error Occurs
sample_list = [25, 30,3 5, 40, 45]
sample_integer = 5
result = sample_list / sample_integer
Here, when trying to work with a division operator with and number and list, the error occurs.
Error message
TypeError: unsupported operand type(s) for /: 'list' and 'int'
If we want to solve this, we need to correct the assignment and how we assigned a variable to list object.
For Loop Method
If you are figuring out how to solve it, the ‘for
’ loop can help. To divide each number and iterate the ‘list, for loop method is used. Check out the example
sample_list = [25, 30,35, 40, 45]
sample_integer = 5
for number in sample_list:
result = number / sample_integer
print(result)
Output
5.0
6.0
7.0
8.0
9.0
If one trying to use the division ‘/
’ operator on any item in the specified list, you need to access the item, especially at its specified index.
sample_list = [25, 30, 35, 40, 45]
sample_integer = 5
result = sample_list[2] / sample_integer
print(result)
Output
7.0
Here, a list item has been accessed at the ‘2’ index which is divided by ‘5’.
sum() Method
To get the sum of the list, this sum()
function has been used. It takes an iterable and returns the total of it. This method sums the items from left to right. Check an example
sample_list = [25, 30, 35, 40, 45]
sample_integer = 5
result = sum(sample_list) / sample_integer
print(result)
Output
35.0
If you use this;
print(sum(sample_list))
Output
175.0
type() Method
This method works on the type()
class which is a built-in class. If you want to know the type of the variable stored in the program, you can use the class type(). It works to return the type of an object.
Have a look at the example
sample_list = [25, 30, 35, 40, 45]
print(type(sample_list))
print(isinstance(sample_list, list))
Output
<class 'list'>
True
The isinstance
function is used, which returns ‘True’ if the object is passed in an instance or passed in the class’s subclasses.
Conclusion
And now, you know the ways to fix TypesError unsupported operand type(s) for /: list and int. I am hoping you can solve the issue and work on the project efficiently.
Leave a comment