Raise elements of tuple as power to another tuple in Python

When it is required to raise elements of one tuple as powers of corresponding elements in another tuple, the zip() method and generator expressions can be used effectively.

The zip() method pairs elements from multiple iterables, creating tuples of corresponding elements. A generator expression provides a memory-efficient way to create new sequences by applying operations to existing data.

Basic Example

Here's how to raise elements of the first tuple to the power of corresponding elements in the second tuple ?

my_tuple_1 = (7, 8, 3, 4, 3, 2)
my_tuple_2 = (9, 6, 8, 2, 1, 0)

print("The first tuple is:")
print(my_tuple_1)
print("The second tuple is:")
print(my_tuple_2)

my_result = tuple(elem_1 ** elem_2 for elem_1, elem_2 in zip(my_tuple_1, my_tuple_2))

print("The tuple raised to power of another tuple is:")
print(my_result)
The first tuple is:
(7, 8, 3, 4, 3, 2)
The second tuple is:
(9, 6, 8, 2, 1, 0)
The tuple raised to power of another tuple is:
(40353607, 262144, 6561, 16, 3, 1)

How It Works

The operation performs element-wise power calculations:

  • 79 = 40353607
  • 86 = 262144
  • 38 = 6561
  • 42 = 16
  • 31 = 3
  • 20 = 1

Using Different Approaches

Using List Comprehension (then convert to tuple)

base_tuple = (2, 3, 4, 5)
power_tuple = (1, 2, 3, 2)

# Using list comprehension
result_list = [base ** power for base, power in zip(base_tuple, power_tuple)]
result_tuple = tuple(result_list)

print("Result:", result_tuple)
Result: (2, 9, 64, 25)

Using map() Function

base_tuple = (2, 3, 4, 5)
power_tuple = (1, 2, 3, 2)

# Using map with lambda
result_tuple = tuple(map(lambda x: x[0] ** x[1], zip(base_tuple, power_tuple)))

print("Result:", result_tuple)
Result: (2, 9, 64, 25)

Handling Different Tuple Lengths

When tuples have different lengths, zip() stops at the shortest tuple ?

tuple1 = (2, 3, 4, 5, 6)
tuple2 = (1, 2, 3)  # Shorter tuple

result = tuple(base ** power for base, power in zip(tuple1, tuple2))

print("Base tuple:", tuple1)
print("Power tuple:", tuple2)
print("Result:", result)
print("Only first 3 elements were processed")
Base tuple: (2, 3, 4, 5, 6)
Power tuple: (1, 2, 3)
Result: (2, 9, 64)
Only first 3 elements were processed

Conclusion

Use generator expressions with zip() for memory-efficient element-wise power operations between tuples. The zip() function automatically handles pairing corresponding elements, while the ** operator performs the power calculation.

Updated on: 2026-03-25T17:10:46+05:30

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements