1

I have a generator that I'd like to be yielded.

def foo():
    a = map(lambda x: x*2, range(5))
    # I want a better way to the next few lines
    # The one that looks more functional
    for i in a:
        yield i

I have maps, filters etc. That I'd like to be yielded, is there an alternative way to do it? I looked in itertools and functools, I couldn't find anything.

Edit:

To be more clearer, I want a way such that it returns one value at each function call.

Vasantha Ganesh
  • 4,570
  • 3
  • 25
  • 33
  • 4
    Search the docs for `yield from` – PM 2Ring Sep 14 '18 at 10:07
  • `yield from a` maybe? – Delgan Sep 14 '18 at 10:08
  • A map object is not a generator (also missing `)`) – Chris_Rands Sep 14 '18 at 10:08
  • The top scoring answer in the linked question has good info about `yield from` https://stackoverflow.com/a/18620655/4014959 – PM 2Ring Sep 14 '18 at 10:13
  • 1
    BTW, I assume it's just a toy example, but using a lambda as the function arg of `map` is a code smell. Write a generatod expression instead. That way you avoid a slow Python function call on each iteration. – PM 2Ring Sep 14 '18 at 10:16
  • @PM2Ring, @Delegan, `yield from a` returns the entire thing, not like when you use `yield` and can get one value at a time. – Vasantha Ganesh Sep 14 '18 at 10:17
  • `yield from some_iterable` does the same thing as `for i in some_iterable: yield i`. If you disagree, show us a [mcve] (with output) that demonstrates the difference. FWIW, I've used `yield from` a lot, it's very handy in recursive generators. – PM 2Ring Sep 14 '18 at 10:35

1 Answers1

2

Try yield from (python version has to be >= 3.3);

def foo():
    a = map(lambda x: x*2, range(5))
    yield from a

Or any version, can use iter:

def foo():
    a = map(lambda x: x*2, range(5))
    return iter(a)

iter is equivalent to generator:

(i for i in seq)

Full example:

def foo():
    a = map(lambda x: x*2, range(5))
    return (i for i in a)

Update:

a = iter(map(lambda x: x*2, range(5)))
def foo():
    return next(a)

print(foo())
print(foo())

Output:

0
2

By the way in this case it's a map, so no need iter:

a = map(lambda x: x*2, range(5))
def foo():
    return next(a)

print(foo())
print(foo())

Output:

0
2
U13-Forward
  • 69,221
  • 14
  • 89
  • 114