- Generators are incredibly simple to create. Define a function, but instead of using return, use the keyword yield:
def my_generator(x): while x: x -= 1 yield x
- Create an instance of the function. Don't forget the argument:
mygen = my_generator(5)
- Call the instance as an argument to next():
next(mygen)
- Continue until iteration stops.