Friday, February 27, 2009

Python yield Statement Tutorial


def producesList(xs):
ys = []
for x in xs:
if x % 4 == 0:
continue
if x % 2 == 0:
ys.append(x * 3)
return ys

def generator(xs):
for x in xs:
if x % 4 == 0:
continue
if x % 2 == 0:
yield x * 3

print '-- producesList'
for x in producesList(range(10)):
print x
print '-- generator'
for x in generator(range(10)):
print x
xs = range(5)
xs.extend(producesList(range(10)))
print '-- producesList'
print xs
ys = range(5)
ys.extend(generator(range(10)))
print '-- generator'
print ys


The output...


$ python ~/Documents/py/yield_tutorial.py
-- producesList
6
18
-- generator
6
18
-- producesList
[0, 1, 2, 3, 4, 6, 18]
-- generator
[0, 1, 2, 3, 4, 6, 18]

No comments: