TypeError: unsupported operand type(s) for -: tuple and int

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Vlad Patana

TypeError: unsupported operand type(s) for -: tuple and int #

The Python "TypeError: unsupported operand type(s) for -: 'tuple' and 'int'" occurs when we try to use the subtraction 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.

typeerror unsupported operand type for minus tuple and int

Here is an example of how the error occurs.

main.py
my_tuple = 15, 30, 45 my_int = 5 # ⛔️ TypeError: unsupported operand type(s) for -: 'tuple' and 'int' result = my_tuple - my_int

We are trying to use the subtraction operator with a tuple and a number.

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

If you declared a tuple by mistake, tuples are constructed in the following ways:

  • Using a pair of parenthesis () creates an empty tuple
  • Using a trailing comma - a, or (a,)
  • Separating items with commas - a, b or (a, b)
  • Using the tuple() constructor

If you need to iterate over the tuple and subtract from each number, use a for loop.

main.py
my_tuple = 15, 30, 45 my_int = 5 for num in my_tuple: result = num - my_int print(result) # 👉️ 10, 25, 40

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

main.py
my_tuple = 15, 30, 45 my_int = 5 result = my_tuple[0] - my_int print(result) # 👉️ 10

We accessed the tuple element at index 0 and subtracted 5 from it.

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

main.py
my_tuple = 15, 30, 45 my_int = 5 # result = my_tuple[0] - my_int result = sum(my_tuple) - my_int print(result) # 👉️ 85 print(sum(my_tuple)) # 👉️ 90

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_tuple = (15, 30, 45) print(type(my_tuple)) # 👉️ <class 'tuple'> print(isinstance(my_tuple, tuple)) # 👉️ 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.

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