The easiest and most efficient way to subtract two numbers in Python is to use the minus (-) operator. Just use the (-) between the two numbers.
k = 21 b = 19 l = k - b print(l) # Output: 2
If the first number is greater than the second, the output will be positive. If it is vice versa, the output will be negative.
k = 21 b = 19 negative = b - k print(negative) # Output: -2
If both numbers are the same, the output will be 0.
kb = 19 kl = 19 zero = kb - kl print(zero) # Output: 0
Alternate ways
Here are three alternate ways:
- Using operator.sub()
- Using a lambda function
- Using a custom function
Approach 1: Using an operator.sub()
Python provides a built-in module called “operator” that we can import and use its “sub()” method to subtract numbers.
import operator first_num = 200 second_num = 143 output = operator.sub(first_num, second_num) print(output) # Output: 57
The operator.sub() method accepts the two numbers for subtraction and returns the output. It is no brainer!
Approach 2: Using a lambda function
Without having a full-fledged function, we can create a lambda function, also known as an anonymous (unnamed) function. It will accept two variables to subtract and return the result.
Here is the one-liner:
print((lambda x, y: x - y)(100, 50)) # Output: 50
In this code, lambda x, y: x-y defines an anonymous function that subtracts y from x. So, 100 – 50 = 50.
Approach 3: Using a custom function
You can think of a custom function as a reusable logic that you can use in multiple places, making your code more organized.
In our case, you can define a subtraction logic in the custom function and call it however you want.
def subtraction(m, n):
return m - n
calculation_1 = subtraction(5, 4)
print(calculation_1)
# Output: 1
calculation_2 = subtraction(5, 5)
print(calculation_2)
# Output: 0
calculation_3 = subtraction(5, 6)
print(calculation_3)
# Output: -1
Here, we called a custom function “subtraction()” three times, each with different values, and each time, it returned a different output.






Tom
We can’t use ‘-‘ directly for floats
>>> 3.1-2.2
0.8999999999999999
Newtum Solutions
WOW, I just read this article and found it very useful and informative.