Q:

Python program to find the modulo of tuple elements

belongs to collection: Python Tuple Programs

0

Example:

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

Modulo of Tuple Elements

We are given two tuples consisting of integer elements. We need to create a Python program to find the modulo of tuple elements.

Input:
tuple1 = (4, 8, 7, 3, 9)
tuple2 = (3, 5, 2, 4, 3)

Output:
(1, 3, 1, 3, 0)

To find the solution, we will be simply iterating over both the tuples performing modulus operation i.e. tulp1 % tuple2 for each element. In python, we can perform the task in multiple ways using one of the multiple methods that are present in the function.

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 the generator expression to perform the modulus operation on both the tuples by zipping the values using zip() method.

# Python program to find the 
# modulo of tuple elements
  
# Initializing and printing Tuples 
myTup1 = (4, 8, 7, 3, 9)
myTup2 = (3, 5, 2, 4, 3)

print("The elements of tuple 1 are " + str(myTup1))
print("The elements of tuple 2 are " + str(myTup2))
  
# Performing tuples modulus operation
retModulo = tuple(ele1 % ele2 for ele1, ele2 in zip(myTup1, myTup2))
print("The elements of resultant tuple of modulo operation are " + str(retModulo))

Output:

The elements of tuple 1 are (4, 8, 7, 3, 9)
The elements of tuple 2 are (3, 5, 2, 4, 3)
The elements of resultant tuple of modulo operation are (1, 3, 1, 3, 0)

Method 2:

Another method to solve the problem is directly using the map() method for mapping the result of the mod operation on each element of the tuples.

# Python program to find the 
# modulo of tuple elements

from operator import mod
  
# Initializing and printing Tuples 
myTup1 = (4, 8, 7, 3, 9)
myTup2 = (3, 5, 2, 4, 3)
print("The elements of tuple 1 are " + str(myTup1))
print("The elements of tuple 2 are " + str(myTup2))
  
# Performing tuples modulus operation
retModulo = tuple(map(mod, myTup1, myTup2))
print("The elements of resultant tuple of modulo operation are " + str(retModulo))

Output:

The elements of tuple 1 are (4, 8, 7, 3, 9)
The elements of tuple 2 are (3, 5, 2, 4, 3)
The elements of resultant tuple of modulo operation are (1, 3, 1, 3, 0)

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 pairwise addition in tup... >>
<< Python program to extract rear element from list o...