173

Is there a modulo function in the Python math library?

Isn't 15 % 4, 3? But 15 mod 4 is 1, right?

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Hick
  • 35,524
  • 46
  • 151
  • 243

7 Answers7

261

There's the % sign. It's not just for the remainder, it is the modulo operation.

eduffy
  • 39,140
  • 13
  • 95
  • 92
60

you can also try divmod(x, y) which returns a tuple (x // y, x % y)

wjandrea
  • 28,235
  • 9
  • 60
  • 81
uolot
  • 1,480
  • 1
  • 13
  • 18
43
>>> 15 % 4
3
>>>

The modulo gives the remainder after integer division.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
28

mod = a % b

This stores the result of a mod b in the variable mod.

And you are right, 15 mod 4 is 3, which is exactly what python returns:

>>> 15 % 4
3

a %= b is also valid.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Merijn
  • 329
  • 2
  • 4
11

Why don't you use % ?


print 4 % 2 # 0
Geo
  • 93,257
  • 117
  • 344
  • 520
5

I don't think you're fully grasping modulo. a % b and a mod b are just two different ways to express modulo. In this case, python uses %. No, 15 mod 4 is not 1, 15 % 4 == 15 mod 4 == 3.

UnsignedByte
  • 849
  • 10
  • 29
2
A = [3, 1, 2, 4]
for a in A:
    print(a % 2)

output:

1
1
0
0
wjandrea
  • 28,235
  • 9
  • 60
  • 81