Unpaking Tuple

Prasad, Ramit ramit.prasad at jpmorgan.com
Mon Oct 8 18:21:26 EDT 2012


Thomas Bach wrote:
> Hi there,
> 
> On Sat, Oct 06, 2012 at 03:08:38PM +0000, Steven D'Aprano wrote:
> >
> > my_tuple = my_tuple[:4]
> > a,b,c,d = my_tuple if len(my_tuple) == 4 else (my_tuple + (None,)*4)[:4]
> >
> 
> Are you sure this works as you expect? I just stumbled over the following:
> 
> $ python
> Python 3.2.3 (default, Jun 25 2012, 23:10:56)
> [GCC 4.7.1] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> split = ['foo', 'bar']
> >>> head, tail = split if len(split) == 2 else split[0], None
> >>> head
> ['foo', 'bar']
> >>> tail
> >>>
> 
> I don't get it! Could someone help me, please? Why is head not 'foo'
> and tail not 'bar'?
> 
> Regards,
> 	Thomas
> --

I think you just need to wrap the else in parenthesis so the
else clause is treated as a tuple. Without the parenthesis 
I believe it is grouping the code like this.

head, tail = (split if len(split) == 2 else split[0] ), None

You want:
head, tail = split if len(split) == 2 else (split[0], None )


Ramit
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  



More information about the Python-list mailing list