Learning to use yield in Python

The use of the yield expression may be confusing for some, but I hope that with some examples it will be easier to understand.

When you use the yield expression in a function creates a generator function instead of a normal one. Here there are some examples of its usage:

1. Yield values of a list:

def generator(l):
   for i in l:
     yield i

g = generator([1, 2, 3])

next(g)
>> 1
next(g)
>> 2
next(g)
>> 3

2. Generate a fibonacci sequence

def fibonacci():
   a, b = 0, 1
   while True:
     yield a
     a, b = b, a + b

f = fibonacci()
next(f)
>> 0
next(f)
>> 1
next(f)
>> 1
next(f)
>> 3

3. Compound interest calculator

def compound_interest_generator(initial_value, interest_rate):
   month = 1
   while month < 10000:
     yield initial_value * (1 + interest_rate)**month
     month+=1

generator = compound_interest_generator(100, 0.5)

next(generator)
>> 150.0
next(generator)
>> 225.0
next(generator)
>> 337.5
next(generator)
>> 506.25
next(generator)
>> 759.375

4. Now it is your turn!!

Here are some ideas so you can practice this concept:

  1. Build a function that yields each letter of a word
  2. Build a function that generates a sequence of odd numbers
  3. Add to the coumpound_interest_generator a fixed month contribution and add that to the result.