Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unpack the first two elements in list/tuple

Tags:

python

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

like image 603
Hanfei Sun Avatar asked Jul 07 '12 00:07

Hanfei Sun


People also ask

How do I unpack a tuple in a list?

Python uses the commas ( , ) to define a tuple, not parentheses. Unpacking tuples means assigning individual elements of a tuple to multiple variables. Use the * operator to assign remaining elements of an unpacking assignment into a list and assign it to a variable.

Does tuple unpacking work with lists?

Unpack a nested tuple and list. You can also unpack a nested tuple or list. If you want to expand the inner element, enclose the variable with () or [] .

How do you get the first element of a tuple in a list?

We can iterate through the entire list of tuples and get first by using the index, index-0 will give the first element in each tuple in a list.


2 Answers

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.

like image 91
Gustav Larsson Avatar answered Oct 21 '22 11:10

Gustav Larsson


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] 
like image 36
Ned Batchelder Avatar answered Oct 21 '22 09:10

Ned Batchelder