Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unpack a list with fewer variables?

Tags:

python

k = [u'query_urls', u'"kick"', u'"00"', u'msg=1212', u'id=11']

>>> name, view, id, tokens = k
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

I need to provide 5 variables to unpack this list. Is there a way to unpack with fewer, so that tokens gets the rest of the list. I don't want to write another line to append to a list....

Thanks.


Of course I can slice a list, assign individually, etc. But I want to know how to do what I want using the syntax above.

like image 291
User007 Avatar asked Mar 15 '12 22:03

User007


People also ask

Can you unpack a list like a tuple?

In Python, unpacking is not limited to tuples only. You can unpack a list or a string with the same syntax. Unpacking is more commonly known as multiple assignment, as it reminds of assigning multiple variables on the same line.

How do you unpack a list in Python?

Summary. Unpacking assigns elements of the list to multiple variables. Use the asterisk (*) in front of a variable like this *variable_name to pack the leftover elements of a list into another list.

How do I unpack a tuple in a list?

Summary. 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.


1 Answers

In Python 3 you can do this: (edit: this is called extended iterable unpacking)

name, view, id, *tokens = k

In Python 2, you will have to do this:

(name, view, id), tokens = k[:3], k[3:]
like image 129
Interrobang Avatar answered Sep 28 '22 05:09

Interrobang