FULL PYTHON FIX · 8 MIN READ
How to Fix ValueError: too many values to unpack in Python
The right-hand side produces more values than the assignment has targets. Count the fields, then choose the targets or a starred remainder that fits the data contract.
Video guide: How to Fix ValueError: too many values to unpack in Python
The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube
Jump to a chapter
Read the video transcript
Select a timestamp to watch that moment on YouTube.
- 00:00
I have one short record containing a name, an age, and a city. This code tries to split it and store the result in name and age. Python reports too many values to unpack, expected two. The error can sound abstract, but it is a count mismatch. The expression on the right produces three pieces; the assignment on the left has two targets. Let us run it without modifying the record so the failure is visible. The split operation itself works. Python stops at the assignment, before the print line can run. We will first print the sequence produced by split, then choose a fix based on the record's actual contract.
- 00:40
If the format promises exactly three fields, we can use three target names. If it allows optional extra fields, a starred target can collect them. We will also test the opposite boundary, too few fields, because solving one mismatch should not leave the parser mysterious for other inputs. Now we can see the three strings produced by splitting at commas. The age is the text 36, not yet an integer. The traceback's expected two came from the two names, name and age, on the left. A two-field record such as Ada comma 36 would fit the original assignment, which is why this kind of bug may appear only when a new field is added to incoming data.
- 01:23
Count before changing code. There is another data-format issue worth separating from the assignment issue. Calling string split on comma is fine for a controlled example in which fields never contain commas. It is not a full CSV parser. A quoted CSV field may contain a comma as part of one value. For real CSV, use Python's csv module. Here, we are deliberately using simple input to show how unpacking works. The parsing step determines the fields; the assignment step determines what the program does with them. In the first run, the record has exactly three fields, so we name all three.
- 02:04
This is a good contract when every record must have a city and should be rejected if it gains a fourth field. We convert the age text to an integer after unpacking. In the second run, the contract allows extra information. The star before extra tells Python to collect any remaining values in a list. It could contain two fields, one field, or no fields at all. That is an intentional flexible shape, not a way to hide unknown data. If your program has to interpret the city or country, give those fields explicit rules instead of merely collecting them. Also remember that starred unpacking still needs values for name and age_text.
- 02:46
It cannot create a missing age. We should validate that boundary before unpacking. If the age text is not an integer, int will raise a separate ValueError and needs its own input handling. The parser strips spaces around each field, checks that at least two fields exist, and only then unpacks the values. The first valid call returns an empty extras list; the second returns London in extras. For a one-field line, our own error message explains what the record lacks. This is clearer than allowing an unpacking error to be the only explanation. Testing a normal case is not enough: check the minimum field count, a record with optional extras, and one invalid record.
- 03:31
Watch the returned shape carefully: the name stays a string, age becomes an integer, and extras is always a list, even when empty. A stable return shape simplifies code that calls the parser. For genuine CSV files, replace this simple split with csv.reader, while keeping the explicit rules about required and optional fields. In a real system you might also reject blank names or impossible ages, but those are additional validation rules beyond today's unpacking mistake. Now write parse_person yourself. The checked task expects a tuple containing a trimmed name, an integer age, and a list of all remaining trimmed fields.
- 04:14
For Ada comma 36, the extras list is empty. For Grace comma 41 comma London comma UK, it contains London and UK. A line with only a name must raise ValueError. As an extra test, try a line with an empty age field, such as Ada comma comma London. The split produces enough fields for unpacking, but converting the empty age text to an integer fails. That is a conversion error rather than a count error, and it needs a separate policy in a production parser. Distinguishing these failures keeps the repair focused and prevents you from hiding bad input behind a broad except block.
- 04:54
When you meet too many values to unpack elsewhere, inspect the entire iterable on the right and count what it yields. Then compare that count with the targets on the left. Use a starred target only when variable-length remainder fields are part of the intended contract. If the format should be fixed, name every required field and let unexpected data surface as a problem. Pause before every assignment and predict the number of items it will yield; that habit catches many count errors before running code. The full guide has runnable examples and links to strings, lists, and tuples so you can practice the pieces independently.
Split a record into too few variables
A small program reads a comma-separated person record. It expects a name and age, but the actual text also contains a city. Run the assignment and inspect the traceback. The split succeeds; the error occurs when Python tries to assign three resulting strings to exactly two target names.
The words expected 2 refer to the two targets on the left side, not to the number of commas. Changing the person's age or converting it to an integer does not repair this mismatch. First inspect the values produced by the expression on the right, then decide how many fields your program truly supports.
record = 'Ada,36,London'
name, age = record.split(',')
print(name, age)ValueError: too many values to unpack (expected 2)Print the sequence before unpacking it
Assign the result of split to one variable and print it with its length. The list has three strings: Ada, 36, and London. Plain unpacking requires one target for each item in this sequence. A shorter line such as Ada,36 would have two items and make the original assignment work, which explains why a bug might appear only after records gain another field.
Splitting on comma is useful for a controlled classroom example, but it is not a complete CSV parser. A quoted field can contain a comma. For actual CSV files or pasted CSV data, use Python's csv module so quoted fields are handled correctly. Keep the source format and the assignment rule separate: the first decides how to parse fields, and the second decides what to do with the parsed values.
record = 'Ada,36,London'
fields = record.split(',')
print(fields)
print(len(fields))['Ada', '36', 'London']
3name, age = 'Ada,36'.split(',')
print(name, age)Ada 36Choose all fields or collect the remainder
If the format always has exactly three fields and your program needs each one, use three target names. This is the clearest contract for a fixed record: an unexpected fourth field will still raise an error and prompt you to check the format. Convert age after unpacking because split returns text, even when that text contains digits.
If the record has at least a name and age but may contain more fields, use a starred target. The star collects zero or more remaining values in a list. This makes extra fields intentional rather than silently throwing them away. It does not solve a record with fewer than two values, so handle that boundary separately. Do not add an arbitrary dummy target just to suppress the exception if the data format can vary.
name, age_text, city = 'Ada,36,London'.split(',')
age = int(age_text)
print(name, age, city)Ada 36 Londonname, age_text, *extra = 'Ada,36,London,UK'.split(',')
print(name)
print(int(age_text))
print(extra)Ada
36
['London', 'UK']Test two, three, and too few fields
Write a small parser with an explicit minimum of two fields. Strip whitespace so Ada, 36 and Ada,36 produce the same age value. Test a two-field line, a line with extras, and a line containing only one field. The function should return a predictable shape for valid lines and raise a clear ValueError for a short line rather than relying on an obscure unpacking failure.
The call to int can still raise ValueError if the age text is not a whole number. That is a different input problem and should be reported or handled according to your application's needs. The lesson about unpacking is to match the number of produced values to the targets deliberately, then verify the boundary cases. A parser's tests should include both the fields it accepts and a malformed record it rejects.
def parse_person(line):
fields = [part.strip() for part in line.split(',')]
if len(fields) < 2:
raise ValueError('Expected at least name and age')
name, age_text, *extra = fields
return name, int(age_text), extra
print(parse_person('Ada,36'))
print(parse_person('Ada,36,London'))('Ada', 36, [])
('Ada', 36, ['London'])def parse_person(line):
fields = [part.strip() for part in line.split(',')]
if len(fields) < 2:
raise ValueError('Expected at least name and age')
name, age_text, *extra = fields
return name, int(age_text), extra
parse_person('Ada')ValueError: Expected at least name and age- Inspect the right-hand sequence to see how many values it produces.
- A starred target collects optional remaining values into a list.
- Validate missing fields before unpacking and handle invalid conversions separately.
Practice the fix
Write parse_person(line) for controlled comma-separated input containing at least a name and integer age. Return (name, age, extras), where extras is a list of all remaining trimmed text fields. Raise ValueError with a useful message when the line has fewer than two fields. Test two fields and several extras.
Need a hint?
Build parts = [part.strip() for part in line.split(',')]. Check len(parts) before writing name, age_text, *extras = parts, then convert age_text with int().
Python console
Ready to runEdit the code and run it in your browser. Examples above can be loaded with Try this example.
Does your code use input()? Add one value per line
Your output appears here.
Write your solution, then select Check practice.
Key takeaways
- Unpacking needs targets that match the values produced, unless a starred target collects the remainder.
- Print a split result and its length to diagnose a mismatch.
- Convert numeric text after unpacking, and validate records with too few fields.
- Use the csv module for real CSV rather than a simple comma split.