[Python-ideas] Unpack of sequences

Guido van Rossum guido at python.org
Wed Aug 29 17:03:49 CEST 2012


On Wed, Aug 29, 2012 at 6:57 AM, Ned Batchelder <ned at nedbatchelder.com> wrote:
> On 8/29/2012 9:50 AM, Carlo Pires wrote:
>>
>> Hi,
>>
>> I was just wondering why unpack of sequences did not follow same behavior
>> of functions parameters. I mean:
>>
>> first, *rest = 'a b c'.split()
>>
>> should work in python, why doesn't it?
>>
>
> It does in Python 3:
>
> Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
>
>>>> first, *rest = 'a b c'.split()
>>>> first
> 'a'
>>>> rest
> ['b', 'c']
>>>>

Note, however, that putting too much faith in the analogy between
assignment and function calls leads to disappointment. E.g. there's a
big difference between

a = 42

and

a = 42,

while there is no difference between

f(42)

and

f(42,)

Also of course assignment has no equivalent to keyword parameters, nor
does it (currently) allow a "lone star" -- although it would be handy
to be able to say

a, b, * = xs

as a shorthand for

a, b, *_ = xs
del _

Also of note: after

a, b, *z = xs

z is a list, whereas in

def foo(a, b, *z): ...

z will be a tuple. (The latter is arguably a design mistake.)

Plus in Pythin 3 you can't say

def foo(a, (b, c), d): ...

whereas the tuple unpacking even supports nested stars:

a, (b, c, *d), e, *f = [1, range(10), 2, 3, 4, 5}

PS. Asking "why does Python not do X" is generally considered a
leading question.

-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list