What are generators in Python?

Generator is a normal function with yield statement instead of a return statement. If a function contains at least one yield statement it becomes a generator function. Difference b/w yield and return statement is that, return terminate the function while yield transfer the control to the caller function and save all its states and later continues from there on successive calls.

Example:--

Fibonacci Numbers--

def fib_series(limit):
    # Initialize first two Fibonacci Numbers
    a, b = 0, 1
    while a < limit:
        yield a
        a, b = b, a + b

for item in fib_series(10):
    print(item)


OUTPUT:--

0
1
1
2
3
5
8

 

Total Views: 506