NumPy power()

The power() function is used to raise the elements of an array to a specified power.

Example

import numpy as np

# create an array for the base values
base = np.array([2, 3, 4])

# create an array for the exponent values
exponent = np.array([2, 3, 4])

# use power() to raise the base values to the power of the corresponding exponent values result = np.power(base, exponent)
print(result) # Output : [ 4 27 256]

power() Syntax

The syntax of power() is:

numpy.power(base, exponent, out=None)

power() Arguments

The power() function takes one argument:

  • base - the input array containing base values
  • exponent - the exponent value or array, which can be a scalar or an array of the same shape as base.
  • out (optional) - the output array where the result will be stored

power() Return Value

The power() function returns an array that contains the elements of the base array raised to the power of the corresponding elements in the exponent array.


Example 1: power() With Scalar Exponent

import numpy as np

# create an array for the base values
base = np.array([1, 2, 3, 4, 5])

# specify the exponent value
exponent = 3

# use power() to raise the base values to the specified exponent result = np.power(base, exponent)
print(result)

Output

[  1   8  27  64 125]

In this example, we have used the power() function to raise each element in the base array to the power of the specified exponent.


Example 2: power() With Array of Exponent Values

import numpy as np

# create an array for the base values
base = np.array([2, 3, 4])

# create an array for the exponent values
exponent = np.array([4, 2, 1])

# use power() to raise the base values to the power of the corresponding exponent values result = np.power(base, exponent)
print(result)

Output

[16  9  4]

Example 3: Use of out Argument in power()

import numpy as np

base = np.array([7, 8, 9, 10, 12])
exponent = 2

# create an empty array with the same shape as the base array
result = np.zeros_like(base)
# calculate the power and store the result in the out_array np.power(base, exponent, out=result)
print(out_array)

Output

[ 49  64  81 100 144]

Here, after specifying out=result, the result of the power operation is stored in the result array.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges