Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Surprising result with a conditional `yield`

I have the following Python code using yield:

def foo(arg):
    if arg:
        yield -1
    else:
        return range(5)

Specifically, the foo() method shall iterate over a single value (-1) if its argument is True and otherwise iterate over range(). But it doesn’t:

>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(foo(True))
[-1]
>>> list(foo(False))
[]

For the last line, I would expect the same result as for the first line ([0, 1, 2, 3, 4]). Why is this not the case, and how should I change the code so that it works?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using yield from seems to fix your function:

import itertools

def foo(arg):
    if arg:
        yield -1
    else:
        yield from range(5)


print(list(foo(True)))
print(list(foo(False)))

Output as requested

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading