un-tuple (newbie)

Peter Otten __peter__ at web.de
Tue Dec 2 14:09:54 CET 2003


Martin Doering wrote:

> I could find out, how to create a tuple with just one member, but I
> can not find out how to get a value from a tuple with just one member.

>>> tpl = "first item",
>>> tpl
('first item',)
>>> tpl[0]
'first item'

You already got the above solution. Here is another one:

>>> item, = tpl
>>> item
'first item'
>>>

The trailing comma looks strange, but works on both sides of '='.
Packing/unpacking of tuples is remarkably flexible:

>>> tpl = (1, 2, ("3a", "3b"))
>>> (one, two, (threeA, threeB)) = tpl
>>> one
1
>>> threeB
'3b'

It works even with function arguments:

>>> def f(a, (b, c)):
...     print a, b, c
...
>>> f(1, (2, 3))
1 2 3
>>>

Peter




More information about the Python-list mailing list