variable length tuple assignment
Tim Chase
python.list at tim.thechases.com
Wed Feb 25 06:35:06 EST 2009
Chris Rebert wrote:
> On Wed, Feb 25, 2009 at 1:16 AM, Helmut Jarausch
> <jarausch at igpm.rwth-aachen.de> wrote:
>> Sorry if this is too simple but I couldn't find.
>>
>> I vaguely remember there is a means to assign a variable length tuple
>> and catch the 'rest' like
>>
>> S="a,b,c,d"
>>
>> (A,B,<list of remaining items>) = S.split(',')
>
> In Python 3.0 (IIRC):
>
> A, B, *rest = S.split(',')
As an aside, as of the last time I read the PEP[1] on this, I
believe it exhausts (or attempts to exhaust) any iterator. IMHO,
I think this exhausting is a bad idea because it prevents things like
def numbers(start=0):
i = start
while True:
yield i
i += 1
CONST_A, CONST_B, CONST_C, *rest = numbers()
which will hang in current Py3.0 until you blow a stack or
overrun your heap somewhere because it will try to exhaust the
infinite loop. It also changes the type from iter() to list()
for the remaining content (not as grevious).
I agree that the "internal star" usage needs to exhaust the iterator:
A, *rest, C, D = s.split(',')
but the terminal-star syntax should be a little more gracious
with iterators.
Anyways, my $0.02 (minus taxes, money for multiple bailouts, and
deflated by economic conditions -- so not worth much :).
-tkc
[1]
http://www.python.org/dev/peps/pep-3132/
More information about the Python-list
mailing list