-1

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?

3
  • Avoid return within generator functions unless you want to prematurely stop iteration. return terminates the function and prevents further execution. you can use for else part: for num in range(5): yield num Commented Apr 25, 2024 at 9:42
  • @Ghorban That's what yield from is for. Commented Apr 25, 2024 at 9:45
  • @deceze Yes, it allows generator functions to delegate control flow to subiterators and I forgot it. I remember after your post. Thank you. These days, I feel less love with python, and wan't go back to the roots: C and Fortran 😀 Commented Apr 25, 2024 at 10:45

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.