np.add(a, b) is the underlying universal function, or ufunc, that Python's + operator dispatches to when either operand is a NumPy array, applying addition to every corresponding pair of elements at C speed rather than looping in Python. When the two arrays don't have identical shapes, NumPy applies its broadcasting rules to try to align them automatically — for example, adding a scalar to an array applies that scalar to every element, and adding a 1D array to a compatible 2D array applies it to every row.
1Understanding np.add()
np.add(a, b) is the underlying universal function, or ufunc, that Python's + operator dispatches to when either operand is a NumPy array, applying addition to every corresponding pair of elements at C speed rather than looping in Python. When the two arrays don't have identical shapes, NumPy applies its broadcasting rules to try to align them automatically — for example, adding a scalar to an array applies that scalar to every element, and adding a 1D array to a compatible 2D array applies it to every row.
Prefer the + operator over calling np.add() directly for everyday code — they're functionally identical, but + is far more common and readable; np.add() itself is more useful when you need to pass an explicit output array via its out= parameter to avoid allocating a new one.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print(np.add(a, b))2Practical Example
Here is a real-world application of np.add() showing how it is used in production NumPy code.
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
row = np.array([10, 20, 30])
print(matrix + row)3Best Practices
Follow these guidelines when working with np.add():
1. Use the + operator for everyday addition; reach for np.add() explicitly mainly when you need its out= parameter to write into a pre-allocated array
2. Understand NumPy's broadcasting rules before relying on adding arrays of different shapes, so unintended broadcasts don't silently produce a wrong result
3. Check that both operands' dtypes are what you expect after an addition, since NumPy may silently upcast to a more general type
Tip: Prefer the + operator over calling np.add() directly for everyday code — they're functionally identical, but + is far more common and readable; np.add() itself is more useful when you need to pass an explicit output array via its out= parameter to avoid allocating a new one.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print(np.add(a, b))