175

Is there a modulo function in the Python math library?

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

3
  • 6
    3 equals 15 mod 4. Commented Jun 13, 2009 at 17:02
  • 2
    You're probably thinking that (15 mod 4 = -1) which is the same as saying (15 mod 4 = 3) Commented Jun 13, 2009 at 17:03
  • 20
    Beware: (-41) % 3 == -2 in C, but (-41) % 3 == 1 in Python stackoverflow.com/questions/828092/… Commented Jun 13, 2009 at 18:19

7 Answers 7

263

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

Sign up to request clarification or add additional context in comments.

Comments

60

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

Comments

43
>>> 15 % 4 3 >>> 

The modulo gives the remainder after integer division.

Comments

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.

Comments

11

Why don't you use % ?

 print 4 % 2 # 0 

Comments

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.

Comments

2
A = [3, 1, 2, 4] for a in A: print(a % 2) 

output:

1 1 0 0 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.