📅 2012-May-03 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ generator, python ⬩ 📚 Archive
A generator function is useful to produce values one by one when needed. It uses the yield statement to return the next value. When a generator function is called, a generator object is produced. By calling next()
on this object, new values can be generated. When the function returns (not yields), then a StopIteration
exception is generated.
# Infinite sequence generator
def sequenceGen():
= 0
i while True:
yield i
+= 1
i
= sequenceGen()
g print( next( g ) ) # 0
print( next( g ) ) # 1
print( next( g ) ) # 2
Tried with: Python 3.2