One of the great features of Python is Generator Functions. Generator functions allow you to convert any function to a generator function by simply including the
yield keyword somewhere in the function body. When a generator function is called, the response is a generator object, which can be iterated over among other things.
To boil this down to basics, generator functions allow you the programmer to create a function which yields one value at a time (and pauses until the next value is requested) until you decide it is done. This opens endless possibilities for converting sequences, creating sequences, filtering, and more.
The following example is a generator function which will take a simple list or iterator and return pairs of (element, previous_element). This is a great use for generators and the
def lineandlast(listish, first=True, last=True): iterator = iter(listish) lastline = next(iterator) if first: yield lastline, None for line in iterator: yield line, lastline lastline = line if last: yield None, lastline
for line, last in lineandlast([1,2,3,4,5]): print(line, last)
1 None 2 1 3 2 4 3 5 4 None 5
There are two keyword arguments,
last, which can be used to control the output of the first and last items on the output example above.