Call function in loop line and store return value to variable to then be used in the loop?

11,980

You can accomplish this using the two-argument version of the iter() built-in function:

for myVar in iter(myFunc, sentinel):
    print myVar

This is equivalent to the following:

while True:
    myVar = myFunc()
    if myVar == sentinel:
        break
    print myVar

From the docs for iter():

If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

Share:
11,980
Mathieson
Author by

Mathieson

Updated on June 28, 2022

Comments

  • Mathieson
    Mathieson almost 2 years

    I want to do something like the following:

    while myFunc() as myVar:
        print myVar
    

    Basically, just call a function in the loop line that will return a value and continue the loop depending on that value, but I would also like to be able to use that value within the loop and I would rather not have to call the function a 2nd time.

    What I would like to avoid:

    while myFunc():
        myVar = myFunc()
        print myVar