Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does python yield imply continue?

I have a for loop that checks a series of conditions. On each iteration, it should yield output for only one of the conditions. The final yield is a default, in case none of the conditions are true. Do I have to put a continue after each block of yields?

def function():
    for ii in aa:
       if condition1(ii):
           yield something1
           yield something2
           yield something3
           continue

       if condition2(ii):
           yield something4
           continue

       #default
       yield something5
       continue
like image 536
345871345 Avatar asked Jul 18 '10 17:07

345871345


People also ask

Does yield stop execution Python?

When the Python yield statement is hit, the program suspends function execution and returns the yielded value to the caller. (In contrast, return stops function execution completely.)

What happens after yield Python?

yield in Python can be used like the return statement in a function. When done so, the function instead of returning the output, it returns a generator that can be iterated upon. You can then iterate through the generator to extract items. Iterating is done using a for loop or simply using the next() function.

Does Python yield return?

Description. Python yield returns a generator object. Generators are special functions that have to be iterated to get the values. The yield keyword converts the expression given into a generator function that gives back a generator object.

What is yield () in Python?

What Is Yield In Python? The Yield keyword in Python is similar to a return statement used for returning values or objects in Python. However, there is a slight difference. The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.


2 Answers

NO, yield doesn't imply continue, it just starts at next line, next time. A simple example demonstrates that

def f():
    for i in range(3):
        yield i
        print i,

list(f())

This prints 0,1,2 but if yield continues, it won't

like image 110
Anurag Uniyal Avatar answered Sep 26 '22 21:09

Anurag Uniyal


Instead of using the continue statement I would suggest using the elif and else statments:

def function():
    for ii in aa:
       if condition1(ii):
           yield something1
           yield something2
           yield something3

       elif condition2(ii):
           yield something4

       else: #default
           yield something5

This seems much more readable to me

like image 29
flashk Avatar answered Sep 25 '22 21:09

flashk