"yield from" another generator but after processing

319 Views Asked by At

How do we yield from another sub-generator, but with transformation/processing?

for example: in code below, main_gen yields x after transformation using f(x)

def f(x):
   return 2*x

def main_gen():
   for x in sub_gen():
      yield f(x)

can this be replaced with yield from and if so how?

def main_gen():
     yield from ***
2

There are 2 best solutions below

2
user2390182 On

You could do:

def main_gen():
    yield from map(f, sub_gen())
   

But then, why not:

def main_gen():
    return map(f, sub_gen())

Which is a lazy iterator anyway.

2
Tomerikoo On

You can always just transform this to a generator expression and yield from that:

def main_gen():
    yield from (f(x) for x in sub_gen())