Open In App

numpy.power() in Python

Last Updated : 17 Nov, 2025
Comments
Improve
Suggest changes
1 Likes
Like
Report

numpy.power() is used to raise each element of one array (arr1) to the power of the corresponding element of another array (arr2). The operation happens element-wise, and both arrays must have the same shape.

Example:

Input: arr1 = arr2 = [2, 3, 4]
Output: [4, 27, 256]
(Each element is raised to the power of itself -> 2², 3³, 4⁴)

Syntax

numpy.power(arr1, arr2, out=None, where=True, casting='same_kind', order='K', dtype=None)

Parameters:

  • arr1: Input array containing base values.
  • arr2: Input array or scalar containing exponent values.
  • out(Optional): output array to store the result.
  • where(Optional): If True, computes the power operation at that position.
  • casting(Optional): Defines how data type casting is handled.
  • order(Optional): Controls memory layout of the output.
  • dtype(Optional): Specifies the data type used during computation.

Examples

Example 1: This example raises each element in a to the power of the corresponding element in b.

Python
import numpy as np

a = np.array([2, 2, 2, 2, 2])
b = np.array([2, 3, 4, 5, 6])
out = np.power(a, b)
print(out)

Output
[ 4  8 16 32 64]

Explanation: np.power(a, b) -> computes 2**2, 2**3, 2**4, 2**5, 2**6

Example 2: This example generates an array using np.arange() and raises all its elements to the same exponent (a scalar value).

Python
import numpy as np

a = np.arange(8)
out = np.power(a, 2)
print(out)

Output
[ 0  1  4  9 16 25 36 49]

Explanation:

  • np.arange(8) creates an array from 0 to 7.
  • np.power(a, 2) squares every element: 0², 1², 2², ….

Example 3: This example shows how to correctly compute powers when the exponent array contains negative values.

Python
import numpy as np

a = np.array([2, 2, 2], dtype=float)
b = np.array([2, -3, 4])
out = np.power(a, b)
print(out)

Output
[ 4.     0.125 16.   ]

Explanation:

  • NumPy does not allow negative exponents for integer bases, so the base must be converted to float.
  • np.power(a, b) computes: 2², 2⁻³ = (1/8), 2⁴.

Explore