How to multiply two tuples of equal length in Python

Tuple

In this post, we will learn how to multiply two tuples of equal length in Python with code examples using zip() method,Using list comprehension,Using Mul module and NumPy module.

1. Using Zip() function to multiply two tuples of equal length


In this example, we are using . Passing both tuples to zip() method with tuple generato to multiply elements of both tuples convert the result to tuple and print the result.

Python Program Example

int_tuple = (1,2,3,4,5)
int_tuple1= (6,7,8,9,10)

#mutiplying the tuples

tuple_mutiplication = tuple(item1 * item2 for item1, item2 in zip(int_tuple, int_tuple1)) 
print('multiplication of two tuples=',tuple_mutiplication)

Output:

multiplication of two tuples= (6, 14, 24, 36, 50)

2. Multiply the tuples using mul operator


In this example we are using the mul module to multiply tuples and converting the multiply result to tuple and printing the result.

Python Program Example

from operator import mul

int_tuple = (1,2,3,4,5)

int_tuple1= (6,7,8,9,10)

#multiplication the tuples using mul operator

tuple_mutiplication = tuple(map(mul, int_tuple, int_tuple1)) 
print('multiplication of two tuples=',tuple_mutiplication)

Output:

multiplication of two tuples= (6, 14, 24, 36, 50)

3. Numpy to multiply two tuples of equal length in Python


In this example, we are using the python NumPy module to multiple two tuples of equal length. Firstly, we are converting tuples to numpy arrays using np.array() method and multiple both tuple and Finally converting Numpy array to tuple Using tuple() method and printing the resulting output.

Python Code Example

import numpy as np


int_tuple = np.array((1,2,3,4,5))

int_tuple1= np.array((6,7,8,9,10))

print(tuple(int_tuple * int_tuple1))

Output

(6, 14, 24, 36, 50)

4. List compreshesion to mutiply two tuples of equal length


In this example we are using comprehension to multiply tuples of equal length and finally printing the result using print() method.

Python Program Example



mytuple = (1,2,3,4,5)
tuple1 = (6,7,8,9,10)



mutiply_result = tuple([value*tuple1[index] for index, value in enumerate(mytuple)])

print(mutiply_result)

Output

(6, 14, 24, 36, 50)

Summary

In this post we have learned multiple ways of how to multiply two tuples of equal length in Python