Many people use return
rather than yield
, but in some cases yield
can be more efficient and easier to work with.
Here is an example which yield
is definitely best for:
return (in function)
import random
def return_dates():
dates = [] # With 'return' you need to create a list then return it
for i in range(5):
date = random.choice(["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th"])
dates.append(date)
return dates
yield (in function)
def yield_dates():
for i in range(5):
date = random.choice(["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th"])
yield date # 'yield' makes a generator automatically which works
# in a similar way. This is much more efficient.
Calling functions
dates_list = return_dates()
print(dates_list)
for i in dates_list:
print(i)
dates_generator = yield_dates()
print(dates_generator)
for i in dates_generator:
print(i)
Both functions do the same thing, but yield
uses three lines instead of five and has one less variable to worry about.
This is the result from the code:
As you can see both functions do the same thing. The only difference is return_dates()
gives a list and yield_dates()
gives a generator.
A real life example would be something like reading a file line by line or if you just want to make a generator.