can generators be nested?

N

news.west.cox.net

This doesn't work, but is there any elegant way to do something like this?

def gen2():
yield "hello"

def gen1():
gen2()
yield "world"

for i in gen1(): print i

---- output ----
hello
world

I'm doing it this way now:

def gen2():
yield "hello"

def gen1():
for i in gen2(): yield i
yield "world"
 
P

Peter Otten

news.west.cox.net said:
This doesn't work, but is there any elegant way to do something like this?

def gen1():
for i in gen2(): yield i
yield "world"

For this special case, you might find itertools.chain() useful:

from itertools import chain

def gen1():
yield "hello"

def gen2():
yield "world"

for s in chain(gen1(), gen2()):
print s

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top