[Python-3000] Using *a for packing in lists and other places

Thomas Wouters thomas at python.org
Sat Mar 15 23:13:54 CET 2008


On Sat, Mar 15, 2008 at 2:58 PM, Terry Reedy <tjreedy at udel.edu> wrote:

>
> | Also, yielding everything from an iterator:
> |
> | >>> def flatten(iterables):
> | ...     for it in iterables:
> | ...         yield *it
>
> Following the general rule above for *exp, that would be the same as yield
> tuple(it).


No. *exp by itself is not valid syntax:

>>> a, b = *c
  File "<stdin>", line 1
SyntaxError: can use starred expression only as assignment target

It needs something to unpack *into*, in the immediate context. So,

>>> a, b = (*c,)

(or [*c]) works, but is effectively the same thing as

>>> a, b = c


>  But that is nearly useless, whereas the the implicit inner for
> loop meaning is quite useful, with, perhaps, a speedup over an explicit
> inner loop.  Since yield is already pretty magical,a bit more might not
> hurt.
>


> But, ... what do you do with
>    yield *a,b,c # a,b,c as above?
> Yield a 5-tuple?  That would clash badly with 'yield *a' not yielding a
> 3-tuple.


It yields a 5-tuple, yes. Does it help your confusion if you write it as:

 >>> yield (*a, b, c)

? The context of the unpacking operation isn't 'yield', it's the tuple you
create with the commas. If you want it to yield all the elements in a,
followed by b and c, you would need:

>>> yield *(*a, b, c)

It's quite like function arguments (except you can only specify *args after
all positional arguments, right now; Guido wants that to change anyway.)

-- 
Thomas Wouters <thomas at python.org>

Hi! I'm a .signature virus! copy me into your .signature file to help me
spread!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-3000/attachments/20080315/a15d52bc/attachment.htm 


More information about the Python-3000 mailing list