unpack the first two elements in list/tuple

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]

Unfortunately, this does not work in Python 2 though.


On Python 3 you can do the following:

>>> a, b, *_ = 1, 3, 4, 5
>>> a
1
>>> b
3

_ is just a place holder for values you don't need


There is no way to do it with the literals that you've shown. But you can slice to get the effect you want:

a, b = [1, 3, 4, 5, 6][:2]

To get the first two values of a list:

a, b = my_list[:2]

Tags:

Python