Reputation: 63072
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.
Upvotes: 0
Views: 2096
Reputation: 7944
If you wanted this behavior just wrap s.split()
in a list:
>>> for (k,v) in [s.split("=")]:
print(k,v)
('abc', 'asflskfjla')
Upvotes: 0
Reputation: 298206
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']
Upvotes: 7
Reputation: 37319
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.
Upvotes: 3