Search code examples
pythonstringfor-loopsplititerable-unpacking

Convert a split string to a tuple results in "too many values to unpack"


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.


Solution

  • 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']