Q:

Python program to perform subtraction of elements of tuples

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Performing subtraction of elements of tuples

In this problem, we are given two tuples and we need to create a Python program that will create a tuple that contains the result of subtraction of elements of the tuples.

Input:
(3, 1, 7, 4), (6, 5, 3, 2)

Output:
(-3, -4, 4, 2)

To perform elementwise subtraction of tuples, we will be a loop over the tuples with the same iterator and then perform the subtraction for each element and return the resultant values.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by using a map() to map the subtraction of elements of both tuples using the lambda function with subtraction operation. Then convert the result of this map() function to a tuple using tuple() method.

# Initialing and printing 
# the two tuples

myTup1 = (3, 1, 7, 4)
myTup2 = (6, 5, 3, 2)

print("The elements of tuple 1 are " + str(myTup1))
print("The elements of tuple 2 are " + str(myTup2))

# Performing Subtraction operation 
# on Tuples 
subsTup = tuple(map(lambda i, j: i - j, myTup1, myTup2))

print("The elements of Subtraction tuple are " + str(subsTup))

Output:

The elements of tuple 1 are (3, 1, 7, 4)
The elements of tuple 2 are (6, 5, 3, 2)
The elements of Subtraction tuple are (-3, -4, 4, 2)

Method 2:

Another method to solve the problem is by using the sub() method from the operator library in Python. We will be using the map() to map the elements of two tuples using subtraction. The lambda function here will be using operator.sub to perform subtraction.

# Python program to perform subtraction 
# of elements of tuples

import operator

# Initialing and printing the 
# two tuples
myTup1 = (3, 1, 7, 4)
myTup2 = (6, 5, 3, 2)
print("The elements of tuple 1 are " + str(myTup1))
print("The elements of tuple 2 are " + str(myTup2))

# Performing Subtraction operation 
# on Tuples 
subsTup = tuple(map(operator.sub, myTup1, myTup2))

print("The elements of Subtraction tuple are " + str(subsTup))

Output:

The elements of tuple 1 are (3, 1, 7, 4)
The elements of tuple 2 are (6, 5, 3, 2)
The elements of Subtraction tuple are (-3, -4, 4, 2)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to check for None tuple... >>
<< Python program to extract unique elements in neste...