regularpython@gmail.com
Python generators
The generator is also a function. The difference between normal function and generator function is,
Normal functions use the return keyword to exit the function but generator function uses yield keyword to exit the function. We have python functions than what is the use of Generator functions.
The main use of the generator function is, to save the memory space and increase performance.
See the below example what is the exact use of generator function,
Normal Function Example:
def doctor(patients):
result = []
for i in patients:
result.append("patient %s checkup completed "%(i))
return result
patients = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
status = doctor(patients)
print(status)
Output:
['patient 1 checkup completed ', 'patient 2 checkup completed ', 'patient 3 checkup completed ', 'patient 4 checkup completed ', 'patient 5 checkup completed ', 'patient 6 checkup completed ', 'patient 7 checkup completed ', 'patient 8 checkup completed ', 'patient 9 checkup completed ', 'patient 10 checkup completed ']
Generator Function Example:
def doctor(patients):
for i in patients:
yield "patient %s checkup completed "%(i)
patients = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
status = doctor(patients)
print(next(status))
print(next(status))
print("Doctor taking Rest..")
print(next(status))
print(next(status))
print(next(status))
print("Doctor taking Rest..")
print(next(status))
print(next(status))
Output:
patient 1 checkup completed
patient 2 checkup completed
Doctor taking Rest..
patient 3 checkup completed
patient 4 checkup completed
patient 5 checkup completed
Doctor taking Rest..
patient 6 checkup completed
patient 7 checkup completed