User007
User007

Reputation: 1559

How do I unpack a list with fewer variables?

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.

Upvotes: 18

Views: 7775

Answers (1)

Interrobang
Interrobang

Reputation: 17434

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:]

Upvotes: 33

Related Questions