Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Generator function in Python

📅 2012-May-03 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 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():
    i = 0
    while True:
        yield i
        i += 1

g = sequenceGen()
print( next( g ) ) # 0
print( next( g ) ) # 1
print( next( g ) ) # 2

Tried with: Python 3.2