0
ValueError: too many values to unpack.

For example, this line apparently causes this error to occur, but as far as I am aware of it is possible for double assignment in Python 3.

first,second = input('two space-separated numbers:')

I haven't the foggiest clue as to what is causing the error.

Veedrac
  • 58,273
  • 15
  • 112
  • 169
Spode
  • 1
  • possible duplicate of [Python ValueError : too many values to unpack, solution?](http://stackoverflow.com/questions/19937261/python-valueerror-too-many-values-to-unpack-solution) –  Sep 27 '14 at 02:34
  • Or maybe [Python ValueError: too many values to unpack](http://stackoverflow.com/questions/7053551/python-valueerror-too-many-values-to-unpack) –  Sep 27 '14 at 02:34
  • This is a supremely unhelpful title... this will mean nothing to other users with the same problem as you in the future. Notice how the linked "duplicate" questions all have titles that make it clear that they ask the same question? – SethMMorton Sep 27 '14 at 05:50

2 Answers2

3

input returns a string. Unpacking will work only if the string has 2 characters:

>>> first, second = 'ot'
>>> first
'o'
>>> second
't'

Otherwise, it will raise an ValueError:

>>> first, second = 'asdf'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

But that is not what you want. Use str.split to split the string. Splitting by ,:

>>> 'hello,world'.split(',')
['hello', 'world']
>>> first, second = 'hello,world'.split(',')  # .split(',', 1)
>>> first
'hello'
>>> second
'world'

Splitting by whitespace:

first, second = input('two space-separated numbers:').split(maxsplit=1)
Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
falsetru
  • 357,413
  • 63
  • 732
  • 636
2

In Python 3, input always returns a string. Trying to assign a string to a list of variables will cause Python to match each element (i.e., character) of the string to a variable, and if the number of variables and the number of characters don't match, you'll get an error just like the one you're seeing. You need to parse the string returned by input in order to convert it to a list of two numbers and then assign those numbers to first, second.

jwodder
  • 54,758
  • 12
  • 108
  • 124