ValueError: need more than 3 values to unpack

Roy Smith roy at panix.com
Sat Jan 21 10:25:29 EST 2006


"Elezar Simeon Papo" <elezarsimeonpapo at yahoo.com> wrote:
>     SCHOOL, DEPART1, DEPART2, DEPART3 = line.split('\t')
> ValueError: need more than 3 values to unpack
> 
> How do I solve this problem and change the program so it does not stop
> if a data record has less than three DEPART values.

The problem is that when you unpack a sequence, you must have exactly the 
same number of variables as you have values.  The idiom I use in a 
situation where I'm not sure how many values I've got in the sequence is:

words = line.split('\t')+ 4 * [None]
firstFourWords = words[0:3]
SCHOOL, DEPART1, DEPART2, DEPART3 = firstFourWords

The first line generates a list of words which is guaranteed to have at 
least 4 elements in it.  The second line gets the first four of those 
words, and the last line unpacks them (in real life, I'd probably have 
combined the second and third lines, but I spread it out here for 
educational purposes).

If line is "HardKnocks\tFoo", you'll end up unpacking ["HardKnocks", "Foo", 
None, None].  Depending on your application, you may want to pad with empty 
strings instead of None.

It would be convenient if string.split() took an optional 'minsplit' 
argument as well as a 'maxsplit'.  Then you could have just done:

school, dept1, dept2, dept3 = line.split ('\t', 4, 4)

but, alas, it doesn't work that way.



More information about the Python-list mailing list