Skip to content Skip to sidebar Skip to footer

How To Fix 'not Enough Values To Unpack (expected 2, Got 1)' Error

I can't for some reason run the code because it says I need two values when I only need one. How to I get past that? I have tried to delete the value but all I got was an error. de

Solution 1:

The error is referring to this line:

country, city = line.split("/")

split("/") returns a list containing the words from the string line, split using the / character. For example, if line is "japan/tokyo", then line.split("/") will return the list

['japan', 'tokyo']

If there is no / character, then the list will just contain 1 element. For example if line is "japan,tokyo", splitting it will just return

['japan,tokyo']

What is happening with country, city = ... is called list unpacking, meaning the 1st element is saved to country and the 2nd element of the list is saved to city. If your list is is ['japan', 'tokyo'], then country will get "japan" and city will get "tokyo". If the number of elements in the right-hand side list does not match the left-hand side variables, you will get a "not enough values to unpack" error.

Now, I cannot see what's in capital_data.txt, but most probably, the line's from your file does not have a / delimiter (ex. "japan, tokyo"). So split-ing the line with / results in just 1 list element ("got 1"), but the left-hand side has 2 variables ("expected 2").

To get past that, you need to match your file reader code with your actual file format, such as maybe using the correct delimiter (replacing /).

Post a Comment for "How To Fix 'not Enough Values To Unpack (expected 2, Got 1)' Error"