Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting instances of the same generator in Python [duplicate]

Say I've got a generator:

def mygen():
    for i in range(10):
        yield i

This works as I would expect: all combinations of i and j

for i in mygen():
    for j in mygen():
        print i, j

I would think these are different instances. Why are they not acting as different instances?

g1 = mygen()
g2 = mygen()

for i in g1:
    for j in g2:
        print i, j

If I try g1.next(), I get an error because there is no data left.

I'm running Python 2.7.1.

like image 740
jtguerin Avatar asked Jan 16 '23 17:01

jtguerin


1 Answers

Iterating over g2 the first time consumes it, so there's nothing left when you try to iterate over it subsequent times.

g1 = mygen()
for i in g1:
    g2 = mygen()
    for j in g2:
        print i, j
like image 120
Ignacio Vazquez-Abrams Avatar answered Jan 30 '23 19:01

Ignacio Vazquez-Abrams