[Python-Dev] Re: syntactic shortcut - unpack to variably sized
list
Nick Coghlan
ncoghlan at iinet.net.au
Sat Nov 20 03:29:50 CET 2004
Terry Reedy wrote:
> "Carlos Ribeiro" <carribeiro at gmail.com> wrote in message
> news:864d37090411190724440dfe38 at mail.gmail.com...
>
>>For more than a few arguments, it seems to be silly to require the
>>user to write it as:
>>a,b,c,d,e = t[0],t[1],t[2],t[3],t[4:]
>
>
> and also impossible.
>
>>>>t=range(10)
>>>>a,b,c,d=t[:4]; e=t[4:]
>>>>a,b,c,d,e
>
> (0, 1, 2, 3, [4, 5, 6, 7, 8, 9])
Hmm. . .
_>>>t = range(10)
_>>>a, b, c, d, e = t[:4] + [t[4:]]
_>>>a, b, c, d, e
_(0, 1, 2, 3, [4, 5, 6, 7, 8, 9])
So this actually can scale (sort of) to longer tuples.
Anyway, I don't have any real objection to iunpack. If it was designed to work
on any iterator (return the first few elements, then return the partially
consumed iterator), I'd be +1 (since, as Carlos pointed out, slicing doesn't
work for arbitrary iterators).
Something like:
_>>>def iunpack(itr, numitems, defaultitem=None):
_... for i in range(numitems):
_... try:
_... yield itr.next()
_... except StopIteration:
_... yield defaultitem
_... yield itr
_>>> g = (x for x in range(10))
_>>> a, b, c, d, e = iunpack(g, 4)
_>>> a, b, c, d, e
_(0, 1, 2, 3, <generator object at 0xa0cd02c>)
_>>> a, b, c, d, e = iunpack(g, 4)
_>>> a, b, c, d, e
_(4, 5, 6, 7, <generator object at 0xa0cd02c>)
_>>> a, b, c, d, e = iunpack(g, 4)
_>>> a, b, c, d, e
_(8, 9, None, None, <generator object at 0xa0cd02c>)
Cheers,
Nick.
I think we're now to the stage of violently agreeing with each other. . .
--
Nick Coghlan | Brisbane, Australia
Email: ncoghlan at email.com | Mobile: +61 409 573 268
More information about the Python-Dev
mailing list