Home »
Python »
Python programs
Python program to perform division operation on tuples
In this program, we are given two tuples. We need to create a Python program to perform division operation on tuples.
Submitted by Shivang Yadav, on December 14, 2021
Tuples in Python are common types of collections that are used commonly for storing data records in python for processing. In fields like data science and AI, we need to process data tuples to extract fruitful information. In this problem, we will create a python program to perform division operation on tuples.
Before going further with the problem, let's recap some basic topics that will help in understanding the solution.
Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.
Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.
Example:
tuple = ("python", "includehelp", 43, 54.23)
Division Operation on Tuples
In this program, we are given two tuples. We need to create a python program to return a tuple that contains the division of elements of the two tuples.
Input:
tuple1 = (4, 25, 7, 9) , tuple2 = (2, 5, 4, 3)
Output:
(2, 5, 1, 3)
Python provides multiple ways to solve the problem and here we will see some of them working.
Method 1:
One method to perform the XOR operation on elements of tuples is by using generator expression with the zip() to map the elements of both tuples using the division operation and create a tuple with resultant values.
# Python program to perform division
# operation on tuples
# Initializing and printing tuple
myTup1 = (4, 25, 7, 9)
myTup2 = (2, 5, 4, 3)
print("The elements of tuple 1 : " + str(myTup1))
print("The elements of tuple 2 : " + str(myTup2))
# Peroforming XOR operation on tuples
divisionTuple = tuple(val1 // val2 for val1, val2 in zip(myTup1, myTup2))
print("The elements of division tuple : " + str(divisionTuple))
Output:
The elements of tuple 1 : (4, 25, 7, 9)
The elements of tuple 2 : (2, 5, 4, 3)
The elements of division tuple : (2, 5, 1, 3)
Method 2:
Another method to solve the problem is by mapping the XOR operation of the tuple elements done using the floordiv() method from the operator library. Then convert the map to a tuple using the tuple() method.
# Python program to perform division
# operation on tuples
import operator
# Initializing and printing tuple
myTup1 = (4, 25, 7, 9)
myTup2 = (2, 5, 4, 3)
print("The elements of tuple 1 : " + str(myTup1))
print("The elements of tuple 2 : " + str(myTup2))
# Performing XOR operation on tuples
divisionTuple = tuple(map(operator.floordiv, myTup1, myTup2))
print("The elements of division tuple : " + str(divisionTuple))
Output:
The elements of tuple 1 : (4, 25, 7, 9)
The elements of tuple 2 : (2, 5, 4, 3)
The elements of division tuple : (2, 5, 1, 3)
Python Tuple Programs »