In another post I mentioned the module operator and explained it gives the remainder of a division. This description works for positive numbers and 5 % 3 gives 2 which is identical to the remainder but -5 % 3 gives 1 which doesn’t make much sense if it is supposed to be the remainder. If you divide 5 by 3 you have 1 + remainder 2 and if you divide -5 by 3 you have -1 with remainder -2. But if you type -5 % 3 in python you will get 1. What is going on? I had to google it to find the answer. This is what I found: A remainder is least positive integer that should be subtracted from a to make it divisible by b (mathematically if, a = q*b + r then 0 ? r < |b|), where a is dividend, b is divisor, q is quotient and r is remainder. This actually works: 5 % 3 gives 2 because 2 is the smallest positive number that you need to subtract from 5 to get a number that is divisible by 3. Similarly -5 % 3 gives 1 because 1 is again the smallest number you have to subtract to from -5 to get a number that is divisible by 3. This is all a bit technical and it is actually the first time it was important for me because I was indexing a list by using index % len(somelist). With this behaviour of the % operator this trick actually also works for negative indices. Which is actually really cool and not something I would have expected in a python beginner lesson. Something I need to remember for the future.
Leave a comment