[Python-Dev] Extending tuple unpacking

Ron Adam rrr at ronadam.com
Tue Oct 11 22:41:01 CEST 2005


Reinhold Birkenfeld wrote:
> Greg Ewing wrote:
> 
>>Guido van Rossum wrote:
>>
>>
>>>BTW, what should
>>>
>>>    [a, b, *rest] = (1, 2, 3, 4, 5)
>>>
>>>do? Should it set rest to (3, 4, 5) or to [3, 4, 5]?
>>
>>Whatever type is chosen, it should be the same type, always.
>>The rhs could be any iterable, not just a tuple or a list.
>>Making a special case of preserving one or two types doesn't
>>seem worth it to me.
> 
> 
> I don't think that
> 
> [a, b, c] = iterable
> 
> is good style right now, so I'd say that
> 
> [a, b, *rest] = iterable
> 
> should be disallowed or be the same as with parentheses. It's not
> intuitive that rest could be a list here.

I wonder if something like the following would fulfill the need?


This divides a sequence at given index's by using an divider iterator on 
it.

class xlist(list):
     def div_at(self, *args):
	""" return a divided sequence """
         return [x for x in self.div_iter(*args)]
     def div_iter(self, *args):
         """ return a sequence divider-iter """
         s = None
         for n in args:
             yield self[s:n]
             s = n
         yield self[n:]

seq = xlist(range(10))

(a,b),rest = seq.div_at(2)

print a,b,rest          # 0 1 [2, 3, 4, 5, 6, 7, 8, 9]

(a,b),c,(d,e),rest = seq.div_at(2,4,6)

print seq.div_at(2,4,6) # [[0, 1], [2, 3], [4, 5], [6, 7, 8, 9]]
print a,b,c,d,e,rest    # 0 1 [2, 3] 4 5 [6, 7, 8, 9]


This addresses the issue of repeating the name of the iterable.

Cheers,
   Ron



More information about the Python-Dev mailing list