NumPy prod()
The numpy.prod() function calculates the product of elements in an array, either across the entire array or along a specified axis.
Syntax
</>
Copy
numpy.prod(a, axis=None, dtype=None, out=None, keepdims=False, initial=1, where=True)
Parameters
| Parameter | Type | Description |
|---|---|---|
a | array_like | Input data whose elements will be multiplied. |
axis | None, int, or tuple of ints, optional | Axis or axes along which to compute the product. Default (None) computes the product of all elements. |
dtype | dtype, optional | The desired data type of the output array. |
out | ndarray, optional | Alternative output array where the result is stored. Must have the same shape as the expected output. |
keepdims | bool, optional | If True, retains reduced dimensions with size one. |
initial | scalar, optional | Starting value for the product calculation. Default is 1. |
where | array_like of bool, optional | Defines which elements to include in the product calculation. |
Return Value
Returns an array with the product of elements along the specified axis. If out is provided, the result is stored there.
Examples
1. Computing the Product of All Elements in an Array
This example calculates the product of all elements in a 1D array.
</>
Copy
import numpy as np
# Define an array
arr = np.array([1, 2, 3, 4])
# Compute the product of all elements
result = np.prod(arr)
# Print the result
print("Product of all elements:", result)
Output:
Product of all elements: 24
