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

User007
  • 1,519
  • 6
  • 22
  • 35

1 Answers1

33

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:]
Interrobang
  • 16,984
  • 3
  • 55
  • 63
  • 1
    Thanks. No wonder why I can't do `*tokens` it's only in Py3. Thanks. That slice method looks really good. Well, I never knew we could do that in a single line. Yet, it gives me this `ValueError: need more than 2 values to unpack`. I am on 2.6.5 – User007 Mar 15 '12 at 22:47
  • 1
    [PEP 3132](http://www.python.org/dev/peps/pep-3132/) descries extended iterable unpacking in Python 3. – agf Mar 15 '12 at 22:47
  • Haha. The parenthesis does the trick. Thanks, and @agf thanks! – User007 Mar 15 '12 at 22:48
  • 2
    Yes, you'll need the parentheses because you need two items on the left, two on the right. – Interrobang Mar 15 '12 at 22:51
  • Folks I have an opposite problem - I have to unpack a list into fewer variables `a,b,c=my_list` If the list contains 2 variables I want c to retain it's old value. Thanks in advance ! – Zakir Dec 05 '18 at 20:37