Generators make the life of a developer very easy but it is a bit tricky to understand. The idea behind having a generator is to create an iterator but it is different from what we have seen till now. Generators are very simple functions in nature and they return an iterable set of elements one by one.
So far we have seen or worked with functions that return a single value but if there is a need to create a function that return multiple values what would you do? Well, in such cases, developers go for generator with a ‘yield’ statement. Generators allow coders to easily retrieve series of values.
The main difference between a generator and other iterator is that every generator is an iterator but the vice versa does not hold true. Look at the code below:
def student_name(): yield("Alex") yield("Mike") yield("Mary") yield("Martin") yield("Erin") stu = student_name() print(stu.__next__()) print(stu.__next__()) print(stu.__next__()) print(stu.__next__()) print(stu.__next__())
when a call is made to the generator, it returns an object, no statements are executed. The function is invoked using the dot(‘.’) notation. The function works till it encounters the ‘yied’ statement and then returns the value that it has at that time.
Please note that the older versions of python used next() function to retrieve a value but in Pyhton 3 next() is replaced by __next__().
Now to get a better understanding of generators, try the following code:
def student_name(): student = ["Alex","Mike","Mary","Martin","Erin"] for item in student: yield item stu = student_name() print(stu.__next__())
When you run the above code the output is “Alex”. The function executes till it encounters ‘yield’ statement. The function resumes operation only when we call the __next__() method. So, if you now type print(stu.__next__()) in the Python shell the next value will be displayed.