Q:

Python program to find modulo of tuple elements

belongs to collection: Python Tuple Programs

0

Example:

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

Modulo of Tuple Elements

Modulus operator is used in returning the remainder value from the division of two values.

In this program, we are given two tuples with integer values as their elements. We will be creating a program to find the modulo of the elements of these two tuples.

Input: 
Tup1 = (8, 20, 6)
Tup2 = (3, 5, 7)

Output:
(2, 0, 6)

To find the modulo of tuple elements, we need to iterate over all elements of both tuples and perform modulus operation on each element pair and return the resultant value.

All Answers

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

Method 1:

One way is using the generator expression to create a new tuple consisting of values that is the result of modulus operation of elements of both tuples extracted using the zip() method.

# Python program to find modulo of tuple elements

# Initializing and printing both tuple values
tup1 = (8, 20, 6)
tup2 = (3, 5, 7)
print("The elements tuple 1 : " + str(tup1))
print("The elements tuple 2 : " + str(tup2))

# Finding modulo of tuple elements 
modTuple = tuple(val1 % val2 for val1, val2 in zip(tup1, tup2))

# Printing result
print("The modulo of tuple elements : " + str(modTuple))

Output:

The elements tuple 1 : (8, 20, 6)
The elements tuple 2 : (3, 5, 7)
The modulo of tuple elements : (2, 0, 6)

Method 2:

An alternate combination that will solve the problem is using the map() method to map all the modulus values of both tuple elements found using the mod operator imported from the operator library. Then converting this map to a tuple using the tuple() method.

# Python program to find modulo of tuple elements

# Importing operator library 
import operator

# Initializing and printing both tuple values
tup1 = (8, 20, 6)
tup2 = (3, 5, 7)
print("The elements tuple 1 : " + str(tup1))
print("The elements tuple 2 : " + str(tup2))

# Finding modulo of tuple elements 
modTuple = tuple(map(operator.mod, tup1, tup2))

# Printing result
print("The modulo of tuple elements : " + str(modTuple))

Output:

The elements tuple 1 : (8, 20, 6)
The elements tuple 2 : (3, 5, 7)
The modulo of tuple elements : (2, 0, 6)

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 perform division operation on tu... >>
<< Python program to extract maximum value in record ...