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

Live Demo

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.
Updated on: 2021-03-12T05:33:54+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements