pythonunpack

Unpack the first two elements in list/tuple


Is there a way in Python to do like this:

a, b, = 1, 3, 4, 5

and then:

>>> a
1
>>> b
3

The above code doesn't work as it will throw

ValueError: too many values to unpack


Solution

  • Just to add to Nolen's answer, in Python 3, you can also unpack the rest, like this:

    >>> a, b, *rest = 1, 2, 3, 4, 5, 6, 7
    >>> a
    1
    >>> rest
    [3, 4, 5, 6, 7]
    

    (this does not work in Python 2)