Wed Apr 20 2022·2 min read
Photo by Josh Hild
The Python "TypeError: unsupported operand type(s) for /: 'tuple' and 'int'"
occurs when we try to use the division
/ operator with a tuple and a number.
To solve the error, figure out how the variable got assigned a tuple and correct
the assignment, or access a specific value in the tuple.
Here is an example of how the error occurs.
my_tuple = 10, 20, 30 my_int = 2 # ⛔️ TypeError: unsupported operand type(s) for /: 'tuple' and 'int' result = my_tuple / my_int
We are trying to use the division operator with a
tuple and a number.
tupleobject and correct the assignment.
If you declared a tuple by mistake, tuples are constructed in the following ways:
()creates an empty tuple
If you need to iterate over the
tuple and divide each number, use a
my_tuple = 10, 20, 30 my_int = 2 for num in my_tuple: result = num / my_int print(result) # 👉️ 5.0, 10.0, 15.0
If you need to use the division operator on an item in the tuple, access the item at its specific index.
my_tuple = 10, 20, 30 my_int = 2 result = my_tuple / my_int print(result) # 👉️ 5.0
We accessed the tuple element at index
0 and divided it by
If you need to get the sum of the tuple, use the
my_tuple = 10, 20, 30 my_int = 2 result = sum(my_tuple) / my_int print(result) # 👉️ 30.0 print(sum(my_tuple)) # 👉️ 60.0
The sum function takes an iterable, sums its items from left to right and returns the total.
sum function takes the following 2 arguments:
|iterable||the iterable whose items to sum|
|start||sums the |
If you aren't sure what type a variable stores, use the built-in
my_tuple = (10, 20, 30) print(type(my_tuple)) # 👉️ <class 'tuple'> print(isinstance(my_tuple, tuple)) # 👉️ True my_int = 2 print(type(my_int)) # 👉️ <class 'int'> print(isinstance(my_int, int)) # 👉️ True
The type class returns the type of an object.
True if the passed in object is an instance or a subclass of
the passed in class.