views:

206

answers:

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
+10  A: 

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.

John Kugelman
And if you need the index `w` in the loop, you can use the `enumerate` built-in function.
Vinay Sajip
And if you only need the first 10 elements, use itertools.islice(testGen(), 10).
Ants Aasma