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

Nick Coghlan ncoghlan at iinet.net.au
Thu Nov 18 12:07:34 CET 2004


Carlos Ribeiro wrote:
> On Thu, 11 Nov 2004 22:50:21 +0100, Johan Hahn <johahn at home.se> wrote:
> 
>>Hi
>>
>>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 am really late on this thread, but anyway, I've come up with another
> approach to solve the problem using iterators. It uses iterator that
> is guaranteed to always return a fixed number of elements, regardless
> of the size of the sequence; when it finishes, it returns the tail of
> the sequence as the last argument. This is a simple-minded proof of
> concept, and it's surely highly optimizable in at least a hundred
> different ways :-)

So the original example becomes:
   a, b, L = itertools.iunpack(L, 2)

(and the 2 is an element count, not an index, so, as you say, there's no need to 
subtract 1)

That's certainly quite tidy, but it has the downside that it still copies the 
entire list as happens in the OP's code (the copying is hidden, but it still 
happens - the original list isn't destroyed until the assignment of the third 
value returned by the iterator).

It's also likely to require a trip to the docs to find out how iunpack works, 
and it doesn't fare well in the 'discovery' category (that is, the solution to 
what should be a fairly basic list operation is tucked away in itertools)

If list.pop gets updated to handle slice objects, then it can modify the list in 
place, and avoid any copying of list elements. "a, b = L.pop(slice(2)" should be 
able to give even better performance than "a = L.pop(0); b = L.pop(0)" (which 
is, I believe, the only current approach that avoids copying the entire list). 
And the list operation stays where it belongs - in a method of list.

Cheers,
Nick.

-- 
Nick Coghlan               |     Brisbane, Australia
Email: ncoghlan at email.com  | Mobile: +61 409 573 268


More information about the Python-Dev mailing list