
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements