This is a sample script to test the use of yield... am I doing it wrong? It always returns '1'...
#!/usr/bin/python
def testGen():
for a in [1,2,3,4,5,6,7,8,9,10]:
yield a
w = 0
while w < 10:
print testGen().next()
w += 1
This is a sample script to test the use of yield... am I doing it wrong? It always returns '1'...
#!/usr/bin/python
def testGen():
for a in [1,2,3,4,5,6,7,8,9,10]:
yield a
w = 0
while w < 10:
print testGen().next()
w += 1
You're creating a new generator each time. You should only call testGen()
once and then use the object returned. Try:
w = 0
g = testGen()
while w < 10:
print g.next()
w += 1
Then of course there's the normal, idiomatic generator usage:
for n in testGen():
print n
Note that this will only call testGen()
once at the start of the loop, not once per iteration.