Main Content

Multiple yields and no loops in a Python generator?

Archive - Originally posted on "The Horse's Mouth" - 2014-12-22 08:13:42 - Graham Ellis

Python generator functions return their results in parts and don't have a return statement but rather a yield statement whenever a results is ready to be returned - typically, the production of a list that's returned all at once is replaced by the production (in a loop) of a series of values, each of which is individually yielded. See [here] for example.

But just like an ordinary function can have multiple returns, so a generator can have multiple yields and indeed there's no need to have a loop at all within a generator - not a common circumstance, but one I can envisage when I want to get
- a start object
- an increment
- an end object
back from a function. The question came up as to whether this was possible during last week's Python Programming Course ... the answer is "yes it is", and I confirmed that by writing a piece of code that's [here]