Meru
Meru

Reputation: 43

How to interpret the operators modulo/% and equality/== in the same line?

def has_lucky_number(nums):
      return any([num % 7 == 0 for num in nums])

Upvotes: 0

Views: 123

Answers (2)

Dr Sank
Dr Sank

Reputation: 86

Check the docs for operation precedence https://docs.python.org/3/reference/expressions.html#evaluation-order

You can see in the table that mult/div (or % modulo) occurs before comparison (== and <=, etc.), so therefore '%' is evaluated before '==' is.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881633

The list comprehension (that's the actual term you need to search for to see how this works, if you don't already know) [num % 7 == 0 for num in nums] will give you a list of True or False values, one for each number in the original list nums.

Each entry will be True if and only if the corresponding entry in nums is a multiple of seven, since x % 7 is the remainder when you divide x by seven - if the remainder was zero then the number was a multiple. In terms of reading the expression itself, num % 7 == 0 is functionally equivalent to (num % 7) == 0,

For example, an original list of [1, 5, 7, 9, 14, 22] would give you the resultant list [False, False, True, False, True, False], since only 7 and 14 from that list satisfy the condition.

Following that, the expression any(someList) will return True if any of the elements of the list are true.

So the entire function as given will simply detect if any element in the list is a multiple of seven, apparently considered "lucky" in the context of this code.

Upvotes: 2

Related Questions