home

dt: 14/01/2025

Understanding the Modulo Operator in Python

The elegant and beautiful background you're seeing started with me implementing Conway's Game of Life in Pygame. Then I remembered Danny Lin's website (he's the creator of OrbStack, an alternative to Docker Desktop for managing VMs easily), where he had it featured. I decided I wanted it on my site too. After some effort, I finally got it working and made it prettier. Now, it's the background of this blog.

-

It does look pretty.

Do you know how the modulo operator (%) works in Python? I'm sure most of us think it just returns the remainder of the division, but we never really dive deeper to understand the logic behind it. Turns out, Python's implementation follows this formula:

a % b = a - b * floor(a / b)

Let's take an example to break it down. Consider 6 % 3:


a = 6
b = 3

6 % 3 = 6 - 3 * floor(6 / 3)
      = 6 - 3 * 2
      = 6 - 6
      = 0
    

I got curious about this while implementing Conway's Game of Life and came across the concept of a toroidal boundary.

Toroidal Boundary and the Modulo Operator

A toroidal boundary (or periodic boundary condition) means the grid wraps around both horizontally and vertically, forming a donut-like shape. If a cell moves off one edge, it reappears on the opposite edge.

Let's say the grid width is 5, so valid column positions are 0, 1, 2, 3, and 4. Now, if we're moving left, the new column is x - 1. But what happens if x = 0? Subtracting 1 gives -1, which is outside the valid range.

To handle this, we use the modulo operator:

LEFT = (x - 1) % width

When x = 0, this gives:

LEFT = (0 - 1) % 5 = 4

This wraps the column around to the last position, keeping everything within the grid.

Modulo Behavior Across Different Languages

One interesting thing to note: the result of the modulo operation in Python takes the sign of the divisor (b). This is different from some other languages.

Example: -10 % 3

In Python:


-10 % 3 = -10 - 3 * floor(-10 / 3)
        = -10 - 3 * -4
        = -10 + 12
        = 2
    

But in C:


a % b = a - b * trunc(a / b)

-10 % 3 = -10 - 3 * trunc(-10 / 3)
        = -10 - 3 * -3
        = -10 + 9
        = -1
    

Why the difference? In C, the division result is truncated towards zero (it just chops off the decimal part), while Python uses flooring. That's why the results aren't the same.

So, next time you use the modulo operator, you'll know it's more than just finding the remainder—there's a bit of math magic behind the scenes!