For the sake of being educational, I will make this a bit long.
In Python, tuples are delimited with parentheses, e.g.: (1, 2, 3)
.
Unfortunately, a tuple consisting of just a single element like 1
would be ambiguous (from a parsing point of view) if specified as simply (1)
, since that could mean the integer one inside parentheses in the middle of an expression.
To overcome that, you can specify a tuple with just one element with the element just followed by a single comma, as in (1,)
. (Just to make it clear, the comma is what makes it a tuple, not the parentheses, which we can omit when things are not ambiguous, and which is what I do below). That is unambiguously the tuple containing a sole single 1
as its element, as is illustrated in the following example:
>>> a = (1)
>>> a
1
>>> b = (1,)
>>> b
(1,)
>>> b[0]
1
>>> c, = b
>>> c
1
>>>
What you mentioned is a way to "unpack" the tuple, that is, to access a specific element of the tuple. One alternative to the syntax that you used is to index the element in the tuple by a 0, like my b[0]
in the example above.
For tuples with more than one element, you can unpack them just by specifying an attribution with the same number of elements that the tuple has:
>>> x, y = (1, 2)
>>> x
1
>>> y
2
If you don't use the same number of elements when unpacking a tuple, you will get an exception being thrown:
>>> z, = (1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>>
In your "example" of why the unpacking theory "fails", you can simply use:
>>> a, _ = [2, 3]
>>> a
2
Note the _
there, which is a usual variable used in Python for the meaning of "we don't care".
As an addendum, note that in a, _ = [2,3]
, you are implicitly creating a tuple, which is an immutable type, from a list, which is a mutable type. (Note that this "implicit" conversion is conceptual, as the Python interpreter may not generate a BUILD_TUPLE
instruction in the bytecode). Note the subtleties in the following attributions:
>>> a, b = [2, 3]
>>> a
2
>>> b
3
>>> a, b
(2, 3)
>>> c, d = tuple([2, 3])
>>> c
2
>>> d
3
>>> e = [2, 3]
>>> type(e)
<type 'list'>
>>> type((a, b))
<type 'tuple'>
a, = [2]
works, you just need to make sure the RHS is a single item sequence - John La Rooya, _ = [2, 3]
works. - rbrito