Search code examples
pythonif-statementbooleanconditional-statementsany

Use any() or all() with break statement logic in Python?


This works:

def gen():
    yield False
    yield True
    yield oups

if any(gen()):
    print('At least one is True')

# At least one is True

But this fails:

if any(iter([False, True, oups])):
    print('At least one is True')

# NameError: name 'oups' is not defined

Is there a way to transform the second code into the first one without too much effort ?


Solution

  • With gen, oups is just a free variable whose lookup never occurs; any stops consuming the generator returned by gen before it becomes necessary.

    With iter([False, True, oups]), however, the list [False, True, oups] first has to be fully created so that it can be passed to iter to return a list iterator. To do that, the lookup of oups has to occur, and because it's not defined, we get a NameError before iter, let alone any, even runs. The second code is evaluated the same as

    t1 = [False, True, oups]  # NameError here
    t2 = iter(t1)
    if any(t2):
        print('At least one is True')