Can Python function return multiple data?

Steven D'Aprano steve at pearwood.info
Sun Jun 7 01:47:52 EDT 2015


On Sun, 7 Jun 2015 03:57 am, fl wrote:

> Excuse me. I input the following according to your idea, but I do not
> understand how to use it from the echo. It does not show how to use
> the multiple output results. I am a new Python user. Please give a little
> more explanation if you could.
> 
> 
> Thanks,
> 
>>>> def func(a):
> yield a*2
> print "a*2"
> yield a*3
> print "a*3"


This is called a "generator function". It is a special type of function that
be stopped and restarted in the middle. Instead of "return", which exits
the function, you use "yield" which provides a result, then pauses the
function waiting to restart at the next line.

When you call x = func(5), it does NOT execute the body of the function.
Instead, it creates a "generator object", or just "generator". When you
display x, you see something like this:

<generator object func at 0x02B97260>

To run the body of func, we need to run x. There are a few different ways.
The usual way is to iterate over it:

for item in x:
    print "item:", item

This will print:

item: 10
a*2
item: 15
a*3

then stop. Do you understand why?

Once you have done this, the generator is exhausted. There are no more
values left, and so we're done with it.

Another way is to pass the generator to a function like list() or tuple().

Remember, because x is exhausted, you have to start with a new generator.
Just run x = func(5) again, and you will have a brand new fresh generator.
Now call list(x), the list function will iterate over the items yielded,
and assemble them into a list or tuple. "a*2" and "a*3" will be printed,
and the list will be [10, 15].


-- 
Steven




More information about the Python-list mailing list