Subtract Two Numbers in Python
Last Updated :
23 Jul, 2025
Subtracting two numbers in Python is a basic operation where we take two numeric values and subtract one from the other. For example, given the numbers a = 10 and b = 5, the result of a - b would be 5. Let's explore different methods to do this efficiently.
Using Minus Operator (-)
This is the most straightforward and common way to subtract two numbers. Just use the minus sign (-) between the numbers.
Python
a = 10
b = 5
res = a - b
print(res)
Explanation: a - b subtracts 5 from 10 and the result is stored in the variable res.
Using operator.sub()
Python's operator module provides a function called sub() for subtraction. It's like telling Python "subtract a from b" explicitly through a function call.
Python
import operator
a = 10
b = 5
res = operator.sub(a, b)
print(res)
Explanation: operator.sub(a, b) expression uses the sub() subtract b from a and the result is stored in the variable res.
Using lambda function
lambda function is an anonymous (unnamed) function. You can use it to subtract two numbers without having to define a full function.
Python
x = lambda a, b: a - b
res = x(10, 5)
print(res)
Explanation: lambda a, b: a - b defines an anonymous function that subtracts b from a. When x(10, 5) is called, it subtracts 5 from 10 and the result is stored in the variable res.
Using function
Defining a function allows you to reuse the subtraction logic in multiple places, making your code more organized. It’s a bit more work but useful if you need to subtract multiple pairs of numbers.
Python
def fun(a, b):
return a - b
r1 = fun(10, 5)
r2 = fun(20,6)
print(r1)
print(r2)
Explanation: fun(a, b) takes two arguments and returns their difference (a - b). When fun(10, 5) is called, it subtracts 5 from 10, storing the result in r1. Similarly, fun(20, 6) subtracts 6 from 20, storing the result in r2.
Related articles
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice