Open In App

numpy.mod() in Python

Last Updated : 10 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

numpy.mod() function returns the element-wise remainder of division between two arrays. It works like the modulo (%) operator but supports broadcasting and array operations.

Example:

Python
import numpy as np
a = np.array([10, 20, 30])
b = np.array([3, 7, 9])
res = np.mod(a, b)
print(res)

Output
[1 6 3]

Explanation: Computes the remainder for each element: 10 % 3 = 1, 20 % 7 = 6, 30 % 9 = 3

Syntax

numpy.mod(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Parameters:

  • x1, x2: Input arrays (or scalars) for which the remainder is calculated.
  • out (optional): A location to store the result.
  • where (optional): Condition array for choosing elements to compute.
  • Other advanced NumPy parameters for casting, ordering, etc.

Returns: An array of remainders with the same shape as input arrays, element-wise.

Examples

Example 1: Using scalar divisor

Python
import numpy as np
a = np.array([5, 8, 12])
res = np.mod(a, 4)
print(res)

Output
[1 0 0]

Explanation: Remainders: 5 % 4 = 1, 8 % 4 = 0, 12 % 4 = 0

Example 2: Negative numbers

Python
import numpy as np
a = np.array([-5, -8, 7])
res = np.mod(a, 4)
print(res)

Output
[3 0 3]

Explanation: In NumPy, mod always returns results with the sign of the divisor: -5 % 4 = 3, -8 % 4 = 0, 7 % 4 = 3.

Example 3: Using broadcasting

Python
import numpy as np
a = np.array([[10, 20], [30, 40]])
b = 6
res = np.mod(a, b)
print(res)

Output
[[4 2]
 [0 4]]

Explanation: Each element is divided by 6 and the remainder is returned.


Similar Reads