
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to get Subtraction of tuples in Python
When it is required to subtract the tuples, the 'map' method and lambda function can be used.
The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.
Anonymous function is a function which is defined without a name. In general, functions in Python are defined using 'def' keyword, but anonymous function is defined with the help of 'lambda' keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it.
Below is a demonstration of the same −
Example
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)
Output
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)
Explanation
- Two tuples are defined, and are displayed on the console.
- The lambda function is used to subtract each of the corresponding elements from the two tuples.
- This operation is mapped to all elements using the 'map' method.
- This result is converted into a tuple.
- This result is assigned to a value.
- It is displayed as output on the console.
- Related Articles
- How to Concatenate tuples to nested tuples in Python
- How to split Python tuples into sub-tuples?
- Python - Get sum of tuples having same first value
- Combining tuples in list of tuples in Python
- Get first element with maximum value in list of tuples in Python
- Count tuples occurrence in list of tuples in Python
- Python program to find Tuples with positive elements in List of tuples
- Remove duplicate tuples from list of tuples in Python
- Addition of tuples in Python
- Python program to find Tuples with positive elements in a List of tuples
- List of tuples to dictionary conversion in Python
- Convert dictionary to list of tuples in Python
- How to Iterate over Tuples in Dictionary using Python
- How does nested character class subtraction work in Python?
- Chunk Tuples to N in Python

Advertisements