# Python Subtraction Operator

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):

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` and `to_remove`, and calculate the difference between them to a new basket `updated_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` and `if` statements.

*** List Comprehension – Ultimate Guide ***

But before we move on, I’m excited to present you 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).

## 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:

1. Get the user input as a string using the built-in `input()` function, and store the result in variables `num_1` and `num_2`.
2. Convert the string user inputs to numerical types using, for example, the `int()` or `float()` constructors.
3. Subtract the numerical values using the subtraction operator `num_1 - num_2`.
4. 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```

## Arithmetic Operators

Arithmetic operators are syntactical shortcuts to perform basic mathematical operations on numbers. 