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

ParameterTypeDescription
aarray_likeInput data whose elements will be multiplied.
axisNone, int, or tuple of ints, optionalAxis or axes along which to compute the product. Default (None) computes the product of all elements.
dtypedtype, optionalThe desired data type of the output array.
outndarray, optionalAlternative output array where the result is stored. Must have the same shape as the expected output.
keepdimsbool, optionalIf True, retains reduced dimensions with size one.
initialscalar, optionalStarting value for the product calculation. Default is 1.
wherearray_like of bool, optionalDefines 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