Generator functions are similar to regular functions except that they return an iterator instead of single (or multiple) values like a regular function. To do this, generator functions use an expression called
So how does
yield differ from a
return statement? Well, any code that is written after a
yield expression will execute on the next iteration of the iterator. Code written after a
return statement will not execute.
The following example shows how the
yield expression is used within a generator function:
def course_generator(): yield 'Computer Science' yield 'Art' yield 'Business'
This function will return an iterator that contains the string values ‘Computer Science’, ‘Art’, and ‘Business’. On each iteration of the iterator, each yield will return its corresponding course value.
courses = course_generator() for course in courses: print(course)
Would print out:
Computer Science Art Business
Another key difference between
return is that the
yield expression will suspend the execution of the function and preserve any local variables that exist within the function. The
return statement will terminate the function immediately and return the result(s) to the caller.
Since generator objects return an iterator object, the function can be called like a normal function and set to an iterator object to then be iterated or looped through as seen in the above
Let’s utilize the
yield keyword to write our own generator function!
We want to create a generator that will generate values of class standings:
'Senior'. The generator function should be named
Initialize an iterator object called
class_standings from calling
for loop to iterate through the
class_standings iterator to print out each class standing value.