General exponentiation
Compute ordinary powers while keeping the operation readable as a function call.
Python · Function
pow() raises a base to an exponent, optionally reducing the result modulo a third argument. Its two-argument form is equivalent to the ** operator, while the three-argument form is optimized for modular exponentiation.
pow() raises base to exp. With mod supplied, it returns that power modulo mod and computes the modular form more efficiently than calculating the power first and then applying %; numeric coercion follows binary arithmetic rules.
pow(base, exp, mod=None)| Name | Type | Description |
|---|---|---|
base | numeric | The number to raise to a power. |
exp | numeric | The exponent applied to base. |
mod | numeric, optional | Optional modulus for modular exponentiation; with integer operands it must be an integer other than zero. |
Returns base raised to exp, or base raised to exp modulo mod when mod is supplied.
result = pow(7, 3, 5)
print(result) # 3
reciprocal = pow(10, -2)
print(reciprocal) # 0.01The three-argument form computes a modular power efficiently; a negative exponent in the two-argument form produces a float.
Compute ordinary powers while keeping the operation readable as a function call.
Perform modular exponentiation efficiently for integer arithmetic.
Calculate reciprocal-style values using a negative exponent, such as pow(10, -2).
pow(base, exp) computes the same value as base ** exp. Adding mod computes the power modulo mod, and this is more efficient than pow(base, exp) % mod.
Follow-up: When is the three-argument form restricted? For integer operands, base, exp, and mod must be integers, and mod cannot be zero.
For integer operands, the result normally retains the operands' type after coercion. If exp is negative, the arguments are converted to float and a float result is returned, such as pow(10, -2) producing 0.01.
Follow-up: What happens with a negative base and a fractional exponent? Python returns a complex result, such as pow(-9, 0.5) being close to 3j.
The built-in pow() accepts base, exp, and an optional mod argument. The optional argument selects modular exponentiation; omitting it gives ordinary exponentiation.
Follow-up: How should modular exponentiation be written? Use pow(base, exp, mod), rather than computing pow(base, exp) % mod, because the documented modular form is more efficient.
**math.pow()%