TypeError: unsupported operand type(s) for /: list and int

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: unsupported operand type(s) for /: list and int #

The Python "TypeError: unsupported operand type(s) for /: 'list' and 'int'" occurs when we try to use the division / operator with a list and a number. To solve the error, figure out how the variable got assigned a list and correct the assignment, or access a specific value in the list.

typeerror unsupported operand type for slash list and int

Here is an example of how the error occurs.

main.py
my_list = [10, 20, 30] my_int = 5 # ⛔️ TypeError: unsupported operand type(s) for /: 'list' and 'int' result = my_list / my_int

We are trying to use the division operator with a list and a number.

To solve the error, you have to figure out how the variable got assigned a list object and correct the assignment.

If you need to iterate over the list and divide each number, use a for loop.

main.py
my_list = [10, 20, 30] my_int = 5 for num in my_list: result = num / my_int print(result) # 👉️ 2.0, 4.0, 6.0

If you need to use the division operator on an item in the list, access the item at its specific index.

main.py
my_list = [10, 20, 30] my_int = 5 result = my_list[0] / my_int print(result) # 👉️ 2.0

We accessed the list item at index 0 and divided it by 5.

If you need to get the sum of the list, use the sum() function.

main.py
my_list = [10, 20, 30] my_int = 5 result = sum(my_list) / my_int print(result) # 👉️ 2.0 print(sum(my_list)) # 👉️ 60

The sum function takes an iterable, sums its items from left to right and returns the total.

The sum function takes the following 2 arguments:

NameDescription
iterablethe iterable whose items to sum
startsums the start value and the items of the iterable. sum defaults to 0 (optional)

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

main.py
my_list = [10, 20, 30] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ 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.

Conclusion #

The Python "TypeError: unsupported operand type(s) for /: 'list' and 'int'" occurs when we try to use the division / operator with a list and a number. To solve the error, figure out how the variable got assigned a list and correct the assignment, or access a specific value in the list.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.