Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get Subtraction of tuples in Python
When you need to subtract corresponding elements of two tuples in Python, you can use the map() function with a lambda expression. This approach applies element-wise subtraction and returns a new tuple with the results.
The map() function applies a given function to every item in an iterable (such as list, tuple). It returns a map object that can be converted to a tuple.
A lambda function is an anonymous function defined without a name. Unlike regular functions defined with def, lambda functions are defined using the lambda keyword and can take any number of arguments but contain only a single expression.
Basic Tuple Subtraction
Here's how to subtract corresponding elements from two tuples ?
my_tuple_1 = (7, 8, 11, 0, 3, 4)
my_tuple_2 = (3, 2, 22, 45, 12, 9)
print("The first tuple is:")
print(my_tuple_1)
print("The second tuple is:")
print(my_tuple_2)
my_result = tuple(map(lambda i, j: i - j, my_tuple_1, my_tuple_2))
print("The tuple after subtraction is:")
print(my_result)
The first tuple is: (7, 8, 11, 0, 3, 4) The second tuple is: (3, 2, 22, 45, 12, 9) The tuple after subtraction is: (4, 6, -11, -45, -9, -5)
How It Works
The process works as follows:
- The
lambda i, j: i - jfunction takes two arguments and returns their difference -
map()applies this lambda function to corresponding elements of both tuples -
tuple()converts the map object back to a tuple - Each element at index n in the result equals
tuple_1[n] - tuple_2[n]
Alternative Approach Using Zip
You can also use zip() with tuple comprehension for the same result ?
tuple_1 = (10, 20, 30, 40)
tuple_2 = (5, 8, 12, 15)
result = tuple(a - b for a, b in zip(tuple_1, tuple_2))
print("Original tuples:", tuple_1, "and", tuple_2)
print("After subtraction:", result)
Original tuples: (10, 20, 30, 40) and (5, 8, 12, 15) After subtraction: (5, 12, 18, 25)
Comparison
| Method | Syntax | Readability |
|---|---|---|
map() + lambda |
tuple(map(lambda i,j: i-j, t1, t2)) |
Concise |
zip() + comprehension |
tuple(a-b for a,b in zip(t1,t2)) |
More readable |
Conclusion
Use map() with lambda for functional programming style tuple subtraction. The zip() with tuple comprehension approach offers better readability for the same element-wise subtraction operation.
