0

Will python's all function exit as soon as it finds a False in the iterable? Or will it continue checking the rest?

For example, if i is not divisible by 20, will the below code continue checking if it is divisible by 19 and 18 and so on?

def min_divisible(target_n):
    '''
    Returns the smallest number that is divisible by all integers between 1 and n
    '''
    i = target_n
    while not all((i%j == 0) for j in range(target_n,2,-1)):
        i+=target_n
    return f'{i:,}'

print(min_divisible(20))
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
awhitin2
  • 29
  • 4

1 Answers1

3

all will stop the iteration as soon as it encounters a "falsey" object. You can see this with a simple example:

def produce_numbers():
    for k in range(10):
        yield k
        print(k)

all(k < 3 for k in produce_numbers())

This prints

0
1
2

This is spelled out in Python's documentation. It states that the following is a functionally equivalent definition of all:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • 1
    This is true if you use a lazy generator as a parameter. But if you use a list comprehension for example, the entire list will be created before the `all` function is called and the early return is irrelevant. – Mark Ransom Jun 05 '22 at 02:28
  • @MarkRansom What does that have to do with `all` and the question and this answer, though? – Kelly Bundy Jun 05 '22 at 04:25
  • I think he’s adding a warning that you won’t enjoy this short-circuit feature if you pass in a list. That’s a very good tip because I’ve seen a lot of code where this occurs. – Daniel Walker Jun 05 '22 at 04:27
  • The *"This is true if"* sounds like the "this" (your answer) isnt true if not, though. I.e., that something you wrote is wrong. – Kelly Bundy Jun 05 '22 at 04:32
  • Ah, I didn’t take it that way. – Daniel Walker Jun 05 '22 at 04:32
  • 2
    @KellyBundy you're right, I probably could have phrased that better. The answer is absolutely correct, but I wanted to point out a common case where that would be a moot point. You just know somebody's going to be bitten by it, and I'd hate for someone to think they'd been misled. – Mark Ransom Jun 05 '22 at 14:46