0

Using split in a for loop results in the mentioned exception. But when taking the elements indpendent from a for loop it works:

>>> for k,v in x.split("="):
...   print k,v
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>> y =  x.split("=")
>>> y
['abc', 'asflskfjla']
>>> k,v = y
>>> k
'abc'
>>> v
'asflskfjla'

An explanation would be appreciated - and also naturally the proper syntax for the for loop version.

Georgy
  • 12,464
  • 7
  • 65
  • 73
WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560

3 Answers3

7

The for loop expects that each item in the iterable can be unpacked into two variables. So in your case, it'd look something like one of these:

[('a, b'), ('c, d'), ...]
[['a, b'], ['c, d'], ...]
['ab', 'cd', ...]
...

Each item in each of those iterables can be split up into a k and a v component. In your case, they cannot, as the output of x.split('=') is a list of strings with more than two characters:

['abc', 'asflskfjla']
Blender
  • 289,723
  • 53
  • 439
  • 496
  • I wouldn't say two-tuple -- Maybe sequence of length 2 (although even that may not be good enough ...) – mgilson May 18 '13 at 02:40
  • @mgilson: I have to work on that terminology. Something like this? – Blender May 18 '13 at 02:43
  • Yeah. that's about as good as you can do it I think. (generators yielding 2 items also work, so that breaks my terminology with sequences). – mgilson May 18 '13 at 02:45
3

x.split returns a list of strings, as you can see from your y variable. When you iterate over that, it takes the first element of the list 'abc' and tries to bind it to the tuple k, v. Since strings are a sequence type, it tries to assign the characters of the string to the tuple you've asked for - and there are in fact too many values (three letters) to unpack into a two-element tuple.

Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83
0

If you wanted this behavior just wrap s.split() in a list:

>>> for (k,v) in [s.split("=")]:
    print(k,v)  
('abc', 'asflskfjla')
HennyH
  • 7,794
  • 2
  • 29
  • 39