python - Please explain Generator mechanics in this example -


can explain mechanics of why prints 3 lines, instead of 24. know due fact generator function exhausted, how?

def counter_gen(size):     cur=1     while cur <= size:         yield cur         cur +=1  c1=counter_gen(8) c2=counter_gen(3)  x in c1:     y in c2:         print x,y 

c2 reaches end after 3 iterations. iterating on again nothing. that's what's meant "exhausting" iterator. so, after 3 items, stops. outer iterator goes 8 times, because inner iterator goes 3 times, first outer iteration anything. next 7 try iterate on exhausted iterator, , nothing happens.

if want new iteration of c2 start each iteration of c1, write way!

c1=counter_gen(8)  x in c1:     c2=counter_gen(3)     y in c2:         print x, y 

or, away c1 , c2 entirely:

for x in counter_gen(8):     y in counter_gen(3):         print x, y 

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo