[Python-Dev] syntactic shortcut - unpack to variably sized list

Johan Hahn johahn at home.se
Thu Nov 11 22:50:21 CET 2004


As far as I can tell from the archive, this has not been discussed before.
This is the second time in less than a week that I have stumbled over the rather 
clumsy syntax of extracting some elements of a sequence and at the same time 
remove those from the sequence:
>>> L = 'a b 1 2 3'.split(' ')
>>> a,b,L = L[0], L[1], L[2:]

I think it would be nice if the following was legal:
>>> a,b,*L = 'a b 1 2 3'.split(' ')
>>> a, b, L
('a', 'b', ['1', '2', '3'])

Today, if the number of variables on both sides of the equal sign doesn't match, 
an exception is raised (for google reference):
ValueError: unpack list of wrong size 

This new syntax is very similar to the special parameter in function definitions that 
catches all excess arguments, as in def func(p, --> *args <--, **kw):, and so the 
semantics should be what everyone expects. 
Then, if we leave this limiting analogy with the *args parameter and allow the 
catch-the-rest variable to be anywhere in the left-hand side, we arrive at a splice 
syntax that reminds me a little of how prolog deals with lists:
>>> a,*b,c = 'a b 1 2 3'.split(' ')
>>> *a,b,c = b.split(' ')
>>> a,b,c
(['b'], '1', '2')

I believe this would make a nice addition to the language.
(Please cc me in response as I'm not subscribed to py-dev.)


More information about the Python-Dev mailing list