Jay Wang
Jay Wang

Reputation: 2840

How to understand the modulo in all() function in Python?

I know the modulo % in Python means to get the remainder, for example:

print 6 % 4            # 2, because 6 = 1 * 4 + 2
print 4 % 2            # 0, because 4 = 2 * 2 + 0

I also have learned the all() function is like the universal quantification, which return True if all the propositions are True, and its argument should be an itarable.

my_list = [True, True, True, True]
print all(my_list)                    # True

However I am stuck in understanding the following code:

test_num = [3,6,9]

print all (11 % i for i in test_num)        # True

for unknown in (11 % i for i in test_num):
    print unknown, type(unknown)            # 2 <type 'int'>
                                            # 5 <type 'int'>
                                            # 2 <type 'int'>

So, why I can get True value from the iterable whose items are all integers?

Thank you!

Upvotes: 2

Views: 201

Answers (3)

Fran&#231;ois
Fran&#231;ois

Reputation: 325

Did you looked at help(all) ?

Help on built-in function all in module __builtin__:

all(...)
    all(iterable) -> bool

    Return True if bool(x) is True for all values x in the iterable.
    If the iterable is empty, return True.

all() is working on Boolean and return a Boolean. So your integer are Transformed to Boolean, meaning any non zero value return True. So you will get False if any modulo return 0, else you get True.

>>> print all([False,True])
False
>>> print all([True,False])
False
>>> print all([True,True])
True

Upvotes: 1

Vikas Tiwari
Vikas Tiwari

Reputation: 537

Anything other than 0 is taken as true. Since there is no 0 in test_num, all(test_num) will return true.

Try this:

>>> test_num = [2,3,0]
>>> print all(test_num)
False  

Apply the same logic to the for loop and you will get your answer.

Upvotes: 1

L3viathan
L3viathan

Reputation: 27283

If you take an integer in a boolean context (for example in a condition, or explicitely through bool), it returns whether the integer is non-zero:

>>> bool(0)
False
>>> bool(43)
True

So let's look at the code:

(11 % i for i in test_num) is a generator that unrolls to 11 % 3, 11 % 6, and 11 % 9, which turn to 2, 5, and 2. Since they're all non-zero, all returns True.

In effect, this returns True if and only if 11 is divisible by neither 3, 6, nor 9.

Upvotes: 3

Related Questions