Recursive generator in Python 3.5

Chris Angelico rosuav at gmail.com
Mon Oct 31 09:54:46 EDT 2016


On Tue, Nov 1, 2016 at 12:39 AM,  <tpqnnd01 at gmail.com> wrote:
> I have some confuse about the recursive generator where the code mixing Yield and return keywork as below. I understand that "return" keywork just raise StopIteration exception but can not understanding in depth, so, could some one explain me about the actual function of two "return" keyworks in case it have other function and mechanism of for running this code segment below:
>
> <code>
> def fg(args):
>   if not args:
>     yield ""
>     return
>   for i in args[0]:
>     for tmp in fg(args[1:]):
>       yield i + tmp
>   return
> print(list(fg(['abc', 'xyz', '123'])))
> </code>

When you call list() on something, the list constructor will step
through the generator until it returns. The generator function will
run, just like any other function, until it hits a 'return' or falls
off the end.

Imagine that every 'yield ...' is actually 'some_list.append(...)'.
That's really what's happening here. The list you get at the end
consists of all the things yielded.

Don't worry about the mechanism of StopIteration. The point of a
generator is that it produces values by yielding, and when it returns,
it no longer produces any values. This is exactly the same as you'd
get if the function printed those values, or called some other
function, or appended them to a list, or something - it's a way of
generalizing a function so its values can be used in any way you
choose.

ChrisA



More information about the Python-list mailing list