### Stats

Saturday, July 23, 2016
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com

# Exponentiation using builtins: ** and pow()

## Example

Exponentiation can be used by using the builtin `pow`-function or the `**` operator:

``````2 ** 3    # 8
pow(2, 3) # 8
``````

For most (all in Python 2.x) arithmetic operations the result's type will be that of the wider operand. This is not true for `**`; the following cases are exceptions from this rule:

• Base: `int`, exponent: `int < 0`:

``````2 ** -3
# Out: 0.125 (result is a float)
``````
• This is also valid for Python 3.x.

• Before Python 2.2.0, this raised a `ValueError`.

• Base: `int < 0` or `float < 0`, exponent: `float != int`

``````(-2) ** (0.5)  # also (-2.) ** (0.5)
# Out: (8.659560562354934e-17+1.4142135623730951j) (result is complex)
``````
• Before python 3.0.0, this raised a `ValueError`.

The `operator` module contains two functions that are equivalent to the `**`-operator:

``````import operator
operator.pow(4, 2)      # 16
operator.__pow__(4, 3)  # 64
``````

or one could directly call the `__pow__` method:

``````val1, val2 = 4, 2
val1.__pow__(val2)      # 16
val2.__rpow__(val1)     # 16
# in-place power operation isn't supported by immutable classes like int, float, complex:
# val1.__ipow__(val2)
``````