Account Options

  1. Sign in
The old Google Groups will be going away soon, but your browser is incompatible with the new version.
Google Groups Home
« Groups Home
Message from discussion Unpaking Tuple

Received: by 10.66.78.40 with SMTP id y8mr2813450paw.2.1349536118343;
        Sat, 06 Oct 2012 08:08:38 -0700 (PDT)
Path: g9ni27428pbh.1!nntp.google.com!npeer01.iad.highwinds-media.com!news.highwinds-media.com!feed-me.highwinds-media.com!nx02.iad01.newshosting.com!newshosting.com!204.153.247.121.MISMATCH!indigo.octanews.net!news-out.octanews.net!mauve.octanews.net!news.astraweb.com!border5.newsrouter.astraweb.com!not-for-mail
From: Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info>
Subject: Re: Unpaking Tuple
Newsgroups: comp.lang.python
References: <801f0e2c-7d1d-4e91-bec5-78c5e53a70ec@googlegroups.com>
	<mailman.1898.1349519275.27098.python-list@python.org>
	<roy-289A2F.08462806102012@news.panix.com>
MIME-Version: 1.0
Date: 06 Oct 2012 15:08:38 GMT
Lines: 53
Message-ID: <50704975$0$29978$c3e8da3$5496439d@news.astraweb.com>
Organization: Unlimited download news at news.astraweb.com
NNTP-Posting-Host: 6d811213.news.astraweb.com
X-Trace: DXC=29a[Y1QDbTRkR1VMS3E6>\L?0kYOcDh@ZN7:H2`MmAUS[VV1\5dcZ`Z]G;2>V^?kWS2Of6BS7?ncZ:3M=FLJ0WZP<DCTmO=k5TP
X-Received-Bytes: 2465
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

On Sat, 06 Oct 2012 08:46:28 -0400, Roy Smith wrote:

> In article <mailman.1898.1349519275.27098.python-l...@python.org>,
>  Chris Rebert <c...@rebertia.com> wrote:
> 
>> But at any rate:
>> shortfall = 4 - len(your_tuple)
>> your_tuple += (None,) * shortfall # assuming None is a suitable default
>> a, b, c, d = your_tuple
>> 
>> If you also need to handle the "too many items" case, use slicing: a,
>> b, c, d = your_tuple[:4]
> 
> I usually handle both of those cases at the same time:
> 
>>>> a, b, c, d = (my_tuple + (None,) * 4)[:4]


While that's fine for small tuples, if somebody wanted to mess with you, 
and passed (say) a million-item tuple, that would unnecessarily copy all 
million items before throwing all but four away.

For the sake of a two-liner instead of a one-liner, you can avoid such 
nasty surprises:

my_tuple = my_tuple[:4]
a,b,c,d = my_tuple if len(my_tuple) == 4 else (my_tuple + (None,)*4)[:4]

A similar solution:

a,b,c,d = (my_tuple[:4] + (None, None, None, None))[:4]

Here's a dumb one-liner, good for making people laugh at you:

a,b,c,d = (x for i,x in enumerate(my_tuple + (None,)*4) if i < 4)

and an obfuscated solution:

from itertools import izip_longest as izip
a,b,c,d = (None if x == (None,None) else x[0][1] for x in izip(zip
('izip', my_tuple), (None for izip in 'izip')))


But in my opinion, the best solution of all is a three-liner:

if len(my_tuple) < 4:
    my_tuple += (None,)*(4 - len(my_tuple))
a,b,c,d = my_tuple[4:]



-- 
Steven