Search code examples
pythonoperatorsoperator-precedence

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])

Solution

  • 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.