The subtraction operation is one of the most fundamental arithmetic operations in Python. It is used to determine the difference between two numbers or objects. The ‘-‘ operator is used to perform subtraction in Python.
This post provides multiple examples of Python subtraction operators. The examples described in this post are:
- Subtraction of Two Numbers
- Subtract User Input Numbers
- Subtract Multiple Numbers
- Subtraction of Complex Numbers
- Subtract Multiple List
- Subtract Multiple Set
Example 1: Subtraction of Two Numbers
The below code uses the “-” subtraction operator to subtract two numbers:
|print(25 – 5)|
print(10.5 – 5.5)
The input two number integers and float has been subtracted using the Python subtraction operator “-”.
The subtracted value has been displayed.
Example 2: Subtract User Input Numbers
The below code is used to subtract user input numbers using the Python subtraction operator:
|num = input(‘Enter First Number: ‘)|
num1 = input(‘Enter Second Number: ‘)
print(‘Subtraction of Two Input Numbers: ‘, int(num)-int(num1))
The user input numbers are input using the input() function and stored in a variable named “num” and “num1”. The “int()” function converts the string value into integers before performing the subtraction operation.
The input numbers have been subtracted.
Example 3: Subtract Multiple Numbers
The below example is used to subtract more than one number:
The multiple integers and float numbers are subtracted from one another by utilizing the “-” subtraction operator.
The subtraction of given numbers has been calculated.
Example 4: Subtraction of Complex Numbers
The subtraction of complex numbers is calculated using the subtraction operator. Here is an example code:
|num = 2 + 18j|
num1 = 5 + 15j
The complex numbers containing real and imaginary parts are subtracted from each other and printed on the screen.
The subtraction result has been displayed.
Example 5: Subtract Multiple Lists
The below code is used to subtract multiple lists by using the list comprehension:
|list_1 = [10, 20, 30, 40, 50, 60]|
list_2 = [10, 30, 50]
print([i for i in list_1 if not i in list_2])
The list named “list_1” and “list_2” is initialized. The for loop and if not statement is used in the List comprehension to subtract the element of one list from another.
The given lists have been subtracted.
Note: The set, tuple, and other data structures are also subtracted from each other using the above methods.
The Python numbers, such as integers, floats, complex numbers, etc., are subtracted from each other using the Python subtraction operator ”-.” Multiple initialized lists, ser, tuple, dict, etc., can be subtracted from each other using the Python subtraction operator. This Python post presented various examples of subtracting numbers from each other using the Python subtraction operators.