Python provides the subtraction operator -
to subtract one object from another. The semantics of the subtraction depends on the operands’ data types. For example, subtracting two integers performs the arithmetic difference operation whereas subtracting two sets performs the set difference operation. The specific return value of the minus operator is defined in a data types’ __sub__()
magic method.
Have a look at the following examples!
Examples
The – operator on integer operands yields another integer—the mathematical difference of both operands:
>>> 2 - 2 0 >>> 2 - 3 -1 >>> -99 - (-1) -98
If at least one of the operands is a float value, the result is also a float—float is infectious!
>>> 2.0 - 1 1.0 >>> 1 - 2.2 -1.2000000000000002 >>> 44.0 - 2.0 42.0
You can also perform the subtraction operator on Python sets. In this case, it calculates the set difference, i.e., it creates a new set with elements in the first but not in the second operand.
Here’s an example:
>>> {1, 2, 3} - {1, 2} {3} >>> {'Alice', 'Bob'} - {1, 'Bob'} {'Alice'} >>> {1, 2, 3} - {1, 2, 3, 4, 5} set()
What if two operands have an incompatible data type? For example, if you try to subtract a set from a string?
>>> 'hello' - {1, 2, 3} Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> 'hello' - {1, 2, 3} TypeError: unsupported operand type(s) for -: 'str' and 'set'
The result of incompatible addition is a TypeError
. You can fix it by using only compatible data types for the operation.
Can you use the subtraction operator on custom objects? Yes!
Python Subtraction Magic Method
To use the subtraction operator on custom objects, define the __sub__()
dunder method that takes two arguments: self
and other
and returns the result of self - other
. You can define the specific behavior by using the attributes (data) maintained in this object.
In the following code, you create a basket from {'coffee', 'banana', 'bred'}
but then you remove the contents in another basket {'bred'}
from it—for example to prevent double-purchasing:
class Basket: def __init__(self, goods): self.goods = goods def __sub__(self, other): return Basket(self.goods - other.goods) my_basket = Basket({'coffee', 'banana', 'bred'}) to_remove = Basket({'bred'}) updated_basket = my_basket - to_remove print(updated_basket.goods)
The output of this code snippet is the new basket:
{'banana', 'coffee'}
The code consists of the following steps:
- Create the class
Basket
that holds the list contents to store some goods. - Define the magic method
__sub__
that creates a new Basket by combining the sets of goods from the two operands’ baskets. Note that we rely on the already implemented subtraction operator on sets, i.e. set difference, to actually implement the subtraction operator for baskets. - We create two baskets
my_basket
andto_remove
, and calculate the difference between them to a new basketupdated_basket
.
Can You Subtract Lists in Python?
Python doesn’t allow built-in support for the list difference operation, i.e., creating a new list with elements from the first list operand but without the elements from the second list operand. Instead, to subtract lst_2
from list lst_1
, use the list comprehension statement as a filter [x for x in lst_1 if x not in lst_2]
.
Here’s a code example:
lst_1 = [1, 2, 3, 4, 5, 6] lst_2 = [1, 2, 3] difference = [x for x in lst_1 if not x in lst_2]
The output is:
print(difference) # Output: [4, 5, 6]
This code makes use of list comprehension that is a compact way of creating lists. The simple formula is [expression + context]
.
- Expression: What to do with each list element?
- Context: What elements to select? The context consists of an arbitrary number of
for
andif
statements.
You can learn more about list comprehension in this in-depth tutorial with video:
*** List Comprehension – Ultimate Guide ***
Check out my new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Publisher Link: https://nostarch.com/pythononeliners
Python Subtraction Program with User Input
To create a simple subtraction program in Python taking the user’s input and subtracting the provided numbers, you can use the following four steps:
- Get the user input as a string using the built-in
input()
function, and store the result in variablesnum_1
andnum_2
. - Convert the string user inputs to numerical types using, for example, the
int()
orfloat()
constructors. - Subtract the numerical values using the subtraction operator
num_1 - num_2
. - Print the result to the Python shell.
Here are those four steps in Python code:
# Python subtraction program with user input # 1. Get string user inputs representing integers num_1 = input('First number: ') num_2 = input('Second number: ') # 2. Converting strings to ints num_1 = int(num_1) num_2 = int(num_2) # 3. Subtracting numbers result = num_1 - num_2 # 4. Display the result print(num_1, '-', num_2, '=', result)
Here’s an example code execution where I put in integers 44 and 2 and calculated the difference using the subtraction operator:
First number: 44 Second number: 2 44 - 2 = 42
Python Subtraction Operator Chaining
You can chain together two subtraction operators. For example, the expression x - y - z
would first calculate the difference between x
and y
and then subtract z
from the resulting object. Thus, it is semantically identical to ((x - y) - z)
.
Here’s a minimal example:
>>> x = 10 >>> y = 5 >>> z = 2 >>> x - y - z 3 >>> ((x - y) - z) 3
π Recommended Tutorial: How to Subtract Two Lists Element-Wise in Python?
Arithmetic Operators
Arithmetic operators are syntactical shortcuts to perform basic mathematical operations on numbers.
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Calculating the sum of the two operands | 3 + 4 == 7 |
– | Subtraction | Subtracting the second operand from the first operand | 4 - 3 == 1 |
* | Multiplication | Multiplying the first with the second operand | 3 * 4 == 12 |
/ | Division | Dividing the first by the second operand | 3 / 4 == 0.75 |
% | Modulo | Calculating the remainder when dividing the first by the second operand | 7 % 4 == 3 |
// | Integer Division, Floor Division | Dividing the first operand by the second operand and rounding the result down to the next integer | 8 // 3 == 2 |
** | Exponent | Raising the first operand to the power of the second operand | 2 ** 3 == 8 |