When I am using the following code
[i for i in range(-9, 10, 2) if not i%3)]
it gives
> (-9, -3, 3, 9)
Why does it give that answer? What does the 'i%3' mean?
Thank you.
In your example, % is the modulo operator. a % b returns the remainder of a / b.
So in your example, the loop goes through:
[-9, -7, -5, -3, -1, 1, 3, 5, 7, 9]
-9 % 3 is equal to 0, because -9 is divisible by 3, and thus there is no remainder. However, 5 % 3 returns 2, because 3 goes into 5 one time, and 5 - 3 == 2.
not i % 3 is a bit tricky. First, i % 3 is evaluated. If the result is greater than 0, then it is considered True. not is a boolean operator which gets the negative of a boolean. So not True is False (and not False is True).
0 is considered False, so if i % 3 == 0, then i will be included in the new list.
Now, the reason why print("%s %s", ("hello", "world")) prints "hello world" is because that isn't the modulo operator. That's string formatting. The docs will explain it better than me :p. It just happens that % is also used.
i%3 is the remainder when dividing i by 3. However, it's then converted to a boolean (true/false) value by the not operator; python does this by making 0 false and any other number true. So not i%3 is true whenever i%3 is 0; in other words, when i is divisible by 3.
range(-9,10,2) produces integers starting at -9, incrementing by 2, as long as they are less than 10. In other words, odd integers between -9 and +9. So the combination is to select odd integers divisible by 3 between -9 and +9, which are precisely the integers you show (-9, -3, 3, 9)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With