Q:

Python program to perform multiplication operation on tuples

belongs to collection: Python Tuple Programs

0

Example:

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

Performing multiplication 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 multiplication elements.

Input:
tuple1 = (4, 1, 7, 9) , tuple2 = (2, 4, 6, 7)

Output:
(8, 4, 1, 42, 63)

Python provides multiple ways to solve the problem and here we will see some of them working.

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 simply using generator expression where we will map the multiplication of the same index elements of both tuples using the zip() method can create a tuple for the resultant value.

# Python program to perform multiplication 
# operation on Tuples

# Initializing and printing both tuples 
tuple1 = (6, 2, 9, 1)
tuple2 = (8, 6, 4, 2)
print("Tuple 1 : " + str(tuple1))
print("Tuple 2 : " + str(tuple2))

# Performing multiplication operation on tuples
mulTuple = tuple(tup1Ele * tup2Ele for tup1Ele, tup2Ele in zip(tuple1, tuple2))

# Printing result
print("Multiplication tuple : " + str(mulTuple))

Output:

Tuple 1 : (6, 2, 9, 1)
Tuple 2 : (8, 6, 4, 2)
Multiplication tuple : (48, 12, 36, 2)

Method 2:

Another method to solve the problem is by using the map function with mul operator as a working function. And then converting the created map to a tuple using the tuple() method.

# Python program to perform multiplication 
# operation on Tuples

import operator

# Initializing and printing both tuples 
tuple1 = (6, 2, 9, 1)
tuple2 = (8, 6, 4, 2)
print("Tuple 1 : " + str(tuple1))
print("Tuple 2 : " + str(tuple2))

# Performing multiplication operation on tuples
mulTuple = tuple(map(operator.mul, tuple1, tuple2))

# Printing result
print("Multiplication tuple : " + str(mulTuple))

Output:

Tuple 1 : (6, 2, 9, 1)
Tuple 2 : (8, 6, 4, 2)
Multiplication tuple : (48, 12, 36, 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 perform comparison operation on ... >>
<< Python program to check if a tuple is a subset of ...