← Back

Home β€Ί Problems β€Ί ValueError: too many values to unpack

ValueError: too many values to unpack

πŸ› Fix the bug Topic: tuples Difficulty: easy Free

What this problem practises

Tuples are immutable containers that may themselves hold mutable objects, and it is the comma β€” not the parentheses β€” that builds one. Any unpacking where the counts disagree raises ValueError.

This is a fix-the-bug problem: a short program is given in its broken state, and the task is to repair the code so it produces the required output. The interactive editor runs your fixed version in the browser and checks it for you β€” no setup, no local interpreter.

Difficulty: easy β€” the fix or the trick is normally a single line, and a careful read should be enough.

The challenge

This program crashes with ValueError because 2 names cannot hold 3 values. Fix the unpacking so it prints 44.

The code runs in PyDebug’s in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.

The error it raises

Run the broken snippet and Python stops with this exact error: ValueError: too many values to unpack. Match it to the Python errors guide, then repair the line that produced it β€” knowing the message is half the fix.

The snippet

The interactive editor pre-fills exactly this code, broken and ready to repair:

a, b = (1, 16, 27)
print(a + b)

Understand the rule

Unpacking (`a, b = items`) demands an exact 1-to-1 match between the number of target variables on the left and the number of items yielded on the right. If `items` has 3 values while the left side names only 2 variables, Python raises `ValueError: too many values to unpack (expected 2)`.

How to trace it

  1. Python iterates the right-hand object to pull elements into the target variables.
  2. After filling all `k` targets on the left, Python checks whether the iterator is exhausted.
  3. Finding at least one leftover item on the right, Python raises `ValueError: too many values to unpack (expected k)`.
  4. Either match the variable count (`a, b, c = items`), slice the right side (`a, b = items[:2]`), or capture extras with `*rest` (`a, b, *rest = items`).

Common wrong fixes

Rule to remember

Match left-hand variables to right-hand length (or use `a, b, *_ = seq` / `.items()` on dicts) so every unpacked value has a home.

Solve it in the interactive editor β†’

More tuples problems

Keep going