There are two terms involved when we discuss generators.
- Generator-Function : A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.
- Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop
So a generator function returns a generator object that is iterable, i.e., can be used as an Iterator
# A simple generator for Fibonacci Numbers
def fib(limit):
# Initialize first two Fibonacci Numbers
a, b = 0, 1
# One by one yield next Fibonacci Number
while a < limit:
yield a
a, b = b, a + b
# Create a generator object
x = fib(5)
# Iterating over the generator object using next
print(x.next()); # In Python 3, __next__()
print(x.next());
print(x.next());
print(x.next());
print(x.next());
# Iterating over the generator object using for
# in loop.
print("\nUsing for in loop")
for i in fib(5):
print(i)
Output :
0
1
1
2
3
Using for in loop
0
1
1
2
3