Q:

Python program to raise elements of tuple as a power to another tuple

belongs to collection: Python Tuple Programs

0

Example:

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

Raise elements of tuple as a power to another tuple

In this article, we will be creating a python program where we will be given two tuples with integer values and the program will raise the elements of the tuple as the power to another tuple.

Input:
tup1 = (4, 1 ,7, 2)
tupl2 = (2, 5, 3, 8)

Output:
(16, 1, 343, 256)

Explanation:
The values are 42 , 15, 73, 28

For performing the task, we will simply traverse both the tuple with the same index and perform the power operation on the values. This can be done in python in a much easier way, let's explore it.

All Answers

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

Method 1:

One method to perform the task is to use the generator expression which will create a new tuple consisting of values that are the result of exponent operation (done using ** operator). The zip() method is employed to create a new tuple using values of two tuples.

# Python program to raise elements of tuple 
# as a power to another tuple

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

# Raising elements of tuple as power to another tuple
powerTuple = tuple(val1 ** val2 for val1, val2 in zip(tup1, tup2))

print("The resultant power tuple is : " + str(powerTuple))

Output:

The elements of tuple 1 : (4, 1, 7, 2)
The elements of tuple 2 : (2, 5, 3, 8)
The resultant power tuple is : (16, 1, 343, 256)

Method 2:

Another method to solve the problem is by mapping the exponential operation of tuple elements done using the pow() method. Then convert the map to a tuple using tuple() method.

# Python program to raise elements of tuple 
# as a power to another tuple

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

# Raising elements of tuple as power to another tuple
powerTuple = tuple(map(pow, tup1, tup2))

print("The resultant power tuple is : " + str(powerTuple))

Output:

The elements of tuple 1 : (4, 1, 7, 2)
The elements of tuple 2 : (2, 5, 3, 8)
The resultant power tuple is : (16, 1, 343, 256)

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 create a tuple from string and l... >>
<< Python program to perform division operation on tu...