Coding

Modulo in Python: The % Operator With Examples

Modulo in Python is the % operator, and it returns the remainder after dividing the left number by the right one: 17 % 5 is 2. The result takes the sign of the right operand, and a zero on the right raises ZeroDivisionError.

Lines starting with >>> below are example output from a Python prompt. They follow the behaviour described in the Python language reference.

How the % operator works

Read a % b as "what is left of a after taking out as many whole copies of b as fit". With positive numbers it behaves like the remainder you learned in school:

>>> 17 % 5
2
>>> 10 % 5
0
>>> 3 % 7
3
>>> 0 % 5
0

Three things follow from that. When a divides evenly by b, the result is 0. When a is smaller than b, nothing fits, so the result is a itself. And for a positive b, the result is always between 0 and b - 1. That last property is what makes modulo useful for wrapping values into a fixed range.

The language reference puts % at the same priority level as *, / and //. They are evaluated left to right, so 2 + 10 % 4 is 2 + 2, which is 4, and 10 * 3 % 4 is 30 % 4, which is 2. Add parentheses when you want to make the order obvious.

Modulo with negative numbers

This is where Python differs from some other languages. The reference says the modulo operator always yields a result with the same sign as its second operand (or zero), and that the absolute value of the result is strictly smaller than the absolute value of the second operand.

>>> -7 % 3
2
>>> 7 % -3
-2
>>> -7 % -3
-1

The rule comes from an identity in the same section of the reference: x == (x//y)*y + (x%y). Floor division rounds toward minus infinity, so -7 // 3 is -3. Then -3 * 3 + (-7 % 3) has to equal -7, which forces -7 % 3 to be 2. You can check the arithmetic yourself:

>>> (-7 // 3) * 3 + (-7 % 3)
-7

In C, Java and JavaScript the % operator takes the sign of the left operand instead, so -7 % 3 gives -1 there. If you port code between languages, test the negative cases first. For the floor division side of this identity, see division and floor division in Python.

Modulo with floats

The operands do not have to be integers. The reference gives 3.14 % 0.7 as equal to 0.34, since 3.14 equals 4*0.7 + 0.34. When both numbers are exactly representable in binary, the answer is exact:

>>> 7.5 % 2
1.5
>>> 5.0 % 2
1.0

With values such as 3.14 and 0.7, the stored floats are approximations, so the printed result can show extra digits (for example 0.33999999999999986 instead of 0.34). Do not compare float remainders with ==; use math.isclose() or round the result.

The type of the result follows the usual rule: the operands are converted to a common type first, so an int and a float give a float.

Modulo with zero: ZeroDivisionError

The reference states that a zero right argument raises ZeroDivisionError. A zero on the left is harmless.

>>> 5 % 0
Traceback (most recent call last):
  ...
ZeroDivisionError: ...
>>> 0 % 5
0

The message text varies between operations and Python versions (the ... stands for it), but the exception type is the same for %, // and /. If the divisor comes from user input or a count that can be empty, check it before you use it:

def every_nth(items, n):
    if n <= 0:
        raise ValueError("n must be a positive integer")
    return [item for index, item in enumerate(items) if index % n == 0]

Raising a clear ValueError up front tells the caller what was wrong, instead of surfacing a ZeroDivisionError from deep inside the function.

Common uses of modulo

Check whether a number is even or odd

def is_even(number):
    return number % 2 == 0

print(is_even(10))   # True
print(is_even(-3))   # False

Because the divisor is positive, number % 2 is always 0 or 1, even for negative numbers. That is why this test is safe in Python.

Check divisibility

A number is divisible by another when the remainder is zero. The classic FizzBuzz test is exactly that:

for number in range(1, 16):
    if number % 15 == 0:
        print("FizzBuzz")
    elif number % 3 == 0:
        print("Fizz")
    elif number % 5 == 0:
        print("Buzz")
    else:
        print(number)

The same pattern gives the leap year rule: a year is a leap year if it is divisible by 4, except years divisible by 100 that are not also divisible by 400.

def is_leap_year(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

print(is_leap_year(2024))   # True
print(is_leap_year(1900))   # False
print(is_leap_year(2000))   # True

If you need leap year logic for real dates, the standard library already has calendar.isleap(), which is better than rewriting it.

Wrap around a fixed range

Modulo turns an ever-growing counter into an index that cycles. A clock face is the standard example. Five hours after 10 o'clock is 3 o'clock:

>>> (10 + 5) % 12
3

The same idea cycles through a list without an if check for the end:

colors = ["red", "green", "blue"]
position = 0
for _ in range(5):
    print(colors[position])
    position = (position + 1) % len(colors)
# red, green, blue, red, green

Python's sign rule helps here. Stepping backwards with (position - 1) % len(colors) from position 0 gives 2, the last element, and never a negative index. In a language that gives -1 for that expression, you would need an extra correction.

Split a total into units

To turn 200 minutes into hours and minutes, use floor division for the whole units and modulo for the rest:

>>> 200 // 60, 200 % 60
(3, 20)

When you need both numbers, divmod() computes them in one call. The docs say that for integers the result is the same as (a // b, a % b):

>>> hours, minutes = divmod(200, 60)
>>> hours, minutes
(3, 20)

Take every nth item

In a loop, index % n == 0 is true for every nth position starting at 0. It is the usual way to print a progress message every 1,000 rows or to process a batch boundary:

for row_number, row in enumerate(rows, start=1):
    process(row)
    if row_number % 1000 == 0:
        print(f"{row_number} rows done")

See Python f-strings for the format syntax used in the last line.

Get the last digit of a number

For a non-negative integer, number % 10 is its last digit, and number // 10 removes it. Repeating both steps visits every digit:

def digit_sum(number):
    total = 0
    while number > 0:
        total += number % 10
        number //= 10
    return total

print(digit_sum(4721))   # 14

The % operator also formats strings

The reference notes that besides modulo on numbers, % is overloaded by string objects to do old-style, printf-style formatting. If the left operand is a string, it is not a remainder at all:

>>> "Hello, %s" % "world"
'Hello, world'
>>> "%d items" % 5
'5 items'
>>> "%d%%" % 50
'50%'

Inside the format string, %% produces a literal percent sign. This style still works, but f-strings are the usual choice in new code. Seeing % after a quoted string in someone else's code is formatting, not arithmetic.

Classes can also define their own meaning for % with the special methods __mod__() and __rmod__(). That is why the operator can mean different things for different types.

% versus math.fmod()

The math module has math.fmod(x, y), which also returns a remainder but follows the C library rules. The docs say that fmod() gives a result with the sign of x, while Python's x % y gives a result with the sign of y:

>>> import math
>>> -7 % 3
2
>>> math.fmod(-7, 3)
-1.0

fmod() always returns a float. The documentation adds that for float arguments the result of % may not be exactly computable. It gives the example that fmod(-1e-100, 1e100) is -1e-100, but -1e-100 % 1e100 rounds to 1e100. For this reason the docs say fmod() is generally preferred for floats, and % for integers.

Modulo is not defined for complex numbers

The reference says the floor division and modulo operators and divmod() are not defined for complex numbers. If you need a remainder from a complex value, convert it to a float first with abs(), where that makes sense for your problem.

Shorthand: the %= operator

Like the other arithmetic operators, % has an augmented assignment form. x %= n replaces x with x % n:

>>> seconds = 125
>>> seconds %= 60
>>> seconds
5

The full list of arithmetic, comparison and logical operators, with their precedence, is in Python operators explained.

If the result surprises you

  • A negative number where you expected a positive one: the right operand is negative. The result takes its sign.
  • A positive number where another language gives a negative one: Python follows the divisor's sign, not the dividend's. Use math.fmod() if you need the C behaviour.
  • Digits like 0.33999999999999986: float rounding. Round for display, or use the decimal module for exact decimal arithmetic.
  • A string where you expected a number: if the left operand is a str, % formats it. Convert with int() first if the value came from input().

Frequently asked questions

What does % do in Python?
Between two numbers, % is the modulo operator and returns the remainder of dividing the left number by the right one. For example, 17 % 5 is 2, because 5 goes into 17 three times with 2 left over. Placed after a string, % does old-style string formatting instead.
Why is -7 % 3 equal to 2 in Python?
Python's modulo result always has the same sign as the right operand (or is zero). Because floor division rounds toward minus infinity, -7 // 3 is -3, and the remainder that makes the identity x == (x // y) * y + (x % y) hold is 2, since -3 * 3 + 2 is -7.
How do I check if a number is even or odd in Python?
Use n % 2. If n % 2 == 0 the number is even, otherwise it is odd. This works for negative integers too, because the result of % 2 is never negative.
What is the difference between % and math.fmod()?
Python's % gives a result with the sign of the divisor, while math.fmod(x, y) gives a result with the sign of x and always returns a float. The Python documentation says fmod() is generally preferred for floats and % is preferred for integers.
What happens if I use modulo with zero?
A zero on the right side raises ZeroDivisionError, for integers and floats alike. A zero on the left side is fine: 0 % 5 is 0.

Sources