Unpaking Tuple

Joshua Landau joshua.landau.ws at gmail.com
Mon Oct 8 18:32:30 EDT 2012


On 8 October 2012 22:45, Thomas Bach <thbach at students.uni-mainz.de> 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'?
>

Here's a hint:

 >>> split = "ab"
>>> head, tail = split if len(split) == 2 else split[0], None
>>> head, tail
('ab', None)
>>> head, tail = (split if len(split) == 2 else split[0]), None
>>> head, tail
('ab', None)
>>> head, tail = split if len(split) == 2 else (split[0], None)
>>> head, tail
('a', 'b')

Regards,
>         Thomas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121008/95a8e724/attachment.html>


More information about the Python-list mailing list