How to Fix ValueError: not enough values to unpack (and too many values to unpack) in Python

3D vector banner for fixing unpacking value errors in Python tuples and lists.

In Python, iterable unpacking lets you assign the elements of a collection to multiple variables in a single statement (first, second = items). For standard fixed-length unpacking to succeed, the number of variables on the left side of = (or inside a for loop header) must exactly match the number of elements yielded by the iterable on the right side.

When the iterable yields fewer items than target variables, Python halts with ValueError: not enough values to unpack (expected X, got Y). When the iterable yields more items than target variables, Python halts with its mirror twin: ValueError: too many values to unpack (expected X).

Reading the Unpacking ValueError Traceback

Read the traceback from the bottom up. The numbers inside the parentheses tell you the exact mismatch between your target variables and the runtime data:

Traceback (most recent call last):
  File "/var/www/app/main.py", line 2, in <module>
    username, role = line.split(":")
ValueError: not enough values to unpack (expected 2, got 1)
  • expected 2, got 1: You wrote 2 variable names (username, role) on the left, but line.split(":") returned a 1-element list (['admin']) because the string had no ":" delimiter (or was an empty string "").
  • expected 2, got 0: The iterable on the right was completely empty—such as a blank row [] from csv.reader(), "".split(), or a generator that was already exhausted in an earlier loop.
  • expected at least 2, got 1: You used a starred target like a, b, *rest = items, which requires at least 2 items for the mandatory variables a and b, but items only had 1 element.
  • too many values to unpack (expected 2): You wrote 2 variable names on the left, but the iterable yielded 3 or more items.

Tested Environment: Python 3.10.16, NumPy 1.26.3 & Pandas 2.0.0 (Linux) | Python 3.11+ carets and linter/type-checker CLI outputs not run by me; noted from documentation.

Part of: The Ultimate Python Debugging Guide

⚡ The Quick Fix: Match the Target Count, Use maxsplit=1 / partition(), or Add .items()

Choose the fix that matches the operation on your crashing line:

1. Splitting KEY=VALUE Strings (line.split("=")): Use maxsplit=1 or partition("=") When parsing key-value strings, plain line.split("=") fails with not enough values if "=" is missing and fails with too many values if the value itself contains "=" (such as a URL query string). Choose between split("=", maxsplit=1) and partition("=") based on how you want to handle missing delimiters:

line = "DB_URL=postgres://localhost:5432/app?sslmode=require"

# Fails with 'too many values to unpack (expected 2)' because of the second '='!
# key, val = line.split("=")

# Option A: split("=", maxsplit=1) splits only on the FIRST '='.
# Note: Still raises ValueError if '=' is completely missing from the line!
if "=" in line:
    key, val = line.split("=", maxsplit=1)
    print(key, "->", val)

# Option B: str.partition("=") ALWAYS returns a 3-tuple (key, sep, val) and NEVER raises ValueError.
# Warning: Because it never raises, you MUST check 'if sep:' so missing delimiters don't silently set val=""!
key, sep, val = line.partition("=")
if not sep:
    raise ValueError(f"Malformed line (missing '='): {line!r}")

2. Looping Over a Dictionary (for k, v in user:): Call .items() Iterating directly over a dictionary only yields its keys, so Python tries to unpack the characters of each key string into k, v. Call .items() to yield (key, value) 2-tuples:

user = {"id": 101, "role": "admin"}

# Fails! Without .items(), Python iterates over the key strings "id" and "role":
# - On "id" (2 chars), it SILENTLY unpacks k='i', v='d'!
# - On "role" (4 chars), it crashes with ValueError: too many values to unpack (expected 2)!
# for k, v in user:

# Fix: Call .items() to yield (key, value) pairs
for k, v in user.items():
    print(k, v)

3. Ignoring Extra Elements: Use Starred Unpacking (*rest or *_) When you only want the first two elements of a variable-length sequence (with at least 2 elements) and want to absorb any remaining elements, add a starred target:

row = ["Alice", "admin", "2026-10-31", "active"]

# Fails: ValueError: too many values to unpack (expected 2)
# name, role = row

# Fix: Absorb 0 or more trailing elements into *extra (or *_)
name, role, *extra = row
print(name, role, "| Extra:", extra)  # Alice admin | Extra: ['2026-10-31', 'active']

⏱️ The 10-Second Diagnostic: What Your ValueError: not enough values to unpack Looks Like

Find the pattern that matches your crashing line to grab the exact fix in under 15 seconds:

What the Code Looks LikeRoot CauseThe Exact Fix
k, v = line.split(“:”) (not enough / too many values)Line is blank, missing “:”, or contains multiple “:” characters.Use k, sep, v = line.partition(“:”) and check if sep:
for a, b, c in csv.reader(f): (expected 3, got 0 or got 2)CSV file has blank lines ([]) or ragged rows with missing/extra columns.Skip blank rows (if not row: continue) and check len(row) == 3 first.
for k, v in my_dict: (dictionary loop)Iterating a dict yields keys, not (key, value) pairs.Add .items(): for k, v in my_dict.items():
for i, x, y in enumerate(pairs): (expected 3, got 2)enumerate() yields a 2-tuple (index, pair), not 3 flat items.Parenthesize inner pair: for i, (x, y) in enumerate(pairs):
for x, y in zip(pairs): (expected 2, got 1)Passing 1 list to zip() yields 1-tuples ((x, y),).Loop directly for x, y in pairs: (or transpose with zip(*pairs)).
scheme, host, path = urlparse(u) (too many values: expected 3)urlparse() returns a 6-element ParseResult named tuple.Use attributes (p.scheme, p.netloc, p.path) or *_.
a, b = my_generator (expected 2, got 0)Generator or iterator was already consumed earlier in the script.Store in a list first if you need to read it more than once.
for i, a, b in df.iterrows(): (Pandas DataFrame)iterrows() yields a 2-tuple (index, row_series).Use for i, row in df.iterrows(): or for i, a, b in df.itertuples():

Can You Fix This str.split() Unpacking Error?

line = "url=https://example.com?id=42"
key, val = line.split("=")
print(key, val)

Why does line.split("=") raise ValueError: too many values to unpack (expected 2), and what is the best fix?

Table of contents

How Python Unpacks Iterables & Debugging Workflow

How Python Unpacks Iterables Under the Hood (Fixed vs. Starred Unpacking)

At the Python language level, every unpacking assignment (a, b = rhs or for a, b in items:) consumes an iterable and assigns its elements positionally. In CPython specifically (an implementation detail of the reference interpreter), the compiler lowers unpacking targets into one of two bytecode instructions—and the difference between them explains both the error messages and how infinite iterators behave:

  1. Fixed-Length Unpacking (a, b = rhs — CPython’s UNPACK_SEQUENCE):
    • If rhs is a list or tuple, Python checks its length directly.
    • If rhs is a general iterator or generator, Python calls iter(rhs) and pulls at most count + 1 items using next():
      • If the iterator stops before reaching count items (after Y items), Python raises ValueError: not enough values to unpack (expected X, got Y).
      • If the iterator yields a (count + 1)-th item, Python stops pulling immediately and raises ValueError: too many values to unpack (expected X). Because fixed-length unpacking stops at item X + 1, even an infinite iterator like a, b = itertools.count(10) fails immediately on the 3rd item (12) without hanging—and that is also why the error message does not print got Y!
  2. Starred Unpacking (a, b, *rest = rhs or a, *mid, b = rhs — PEP 3132, CPython’s UNPACK_EX):
    • When you include a starred target (*rest or *mid), Python requires at least M items for all mandatory non-starred targets (both before and after the starred target), and collects all remaining items into a list.
    • If rhs yields fewer than M items, Python raises ValueError: not enough values to unpack (expected at least M, got Y).
    • ⚠️ Infinite Iterator Warning with *rest: Unlike fixed-length unpacking, starred unpacking (a, b, *rest = it or a, *mid, b = it) must consume the entire iterator to build the rest list (or find the final item b). Passing an infinite iterator like itertools.count() into a starred unpacking assignment will run forever until Python exhausts system RAM (MemoryError)!

Step-by-Step Debugging Workflow

When an unpacking ValueError crashes a loop or assignment line, follow this 5-step procedure to inspect the offending value:

  1. Read expected X vs. got Y from the traceback: X is the number of variables you wrote on the left side of = (or between for and in); Y is how many items the right-hand side actually produced on the crashing iteration.
  2. Assign the right-hand side to a single temporary variable temp: Replace a, b = expr with temp = expr (or in a loop, replace for a, b in items: with for temp in items:).
  3. Print the length, type, and repr() of temp: Drop this diagnostic inside your loop or right above the crash to catch the exact row or line that broke the unpacking contract:
raw_lines = ["host=localhost", "", "port=8080"]

for idx, line in enumerate(raw_lines):
    parts = line.split("=")
    if len(parts) != 2:
        print(f"Row {idx} failed! Expected 2 parts, got {len(parts)}: line={line!r} -> parts={parts!r}")

Verified Output (Python 3.10.16):

Row 1 failed! Expected 2 parts, got 1: line='' -> parts=['']
  1. Check why the item count differed: Was it a blank line ([''] or [] in csv.reader), a comment line (['# comment']), an extra delimiter inside the value, a missing .items() call on a dict, an un-starred zip(pairs), or a generator that was already consumed?
  2. Fix the parsing boundary or add a guard: Filter out blank/comment lines before unpacking, use str.partition() + if sep: for key-value text, or validate tuple length before unpacking.

Common Causes of ValueError: not enough / too many values to unpack

Here are the ten most frequent ways an unpacking mismatch occurs in Python.

1. Splitting Text with str.split() on Blank Lines, Comments, or Extra Delimiters

When parsing config files, log lines, or HTTP headers with key, val = line.split("="), three edge cases break split():

  1. Blank Lines (""): Calling "".split("=") (with an explicit delimiter) returns a 1-element list [""], raising ValueError: not enough values to unpack (expected 2, got 1). By contrast, calling "".split() (with no arguments, splitting on whitespace) returns an empty list [], raising ValueError: not enough values to unpack (expected 2, got 0)!
  2. Lines Missing the Delimiter (e.g., # comment or "admin"): Returns a 1-element list -> not enough values to unpack (expected 2, got 1).
  3. Lines Containing the Delimiter Inside the Value ("TOKEN=abc=123="): Returns a 4-element list -> ValueError: too many values to unpack (expected 2).
  • The Trigger (Verified 3.10.16):
# Trigger A: Blank line or missing delimiter -> expected 2, got 1
key, val = "".split("=")

# Trigger B: Extra '=' inside the value -> too many values to unpack (expected 2)
key, val = "url=https://example.com?a=1&b=2".split("=")
  • The Fix (str.partition("=") vs. split("=", maxsplit=1)):
  • line.split("=", maxsplit=1) caps the split at 1 (solving Trigger B when "=" appears inside the value), but still raises ValueError: not enough values to unpack (expected 2, got 1) if "=" is missing from line.
  • key, sep, val = line.partition("=") splits on the first "=" and is guaranteed to return a 3-tuple for any string without raising ValueError. However, if "=" is missing, partition("=") returns (line, "", "")—meaning sep is "" and val is silently ""! Always check if sep: (to skip lines without "=") or if not sep: raise ValueError(...) (to reject malformed lines):
for raw_line in ["host=localhost", "invalid_line", "url=https://example.com?a=1&b=2"]:
    key, sep, val = raw_line.partition("=")
    if not sep:
        print(f"Skipping line without '=': {raw_line!r}")
        continue
    print(f"{key} => {val}")
# Prints:
# host => localhost
# Skipping line without '=': 'invalid_line'
# url => https://example.com?a=1&b=2

2. Unpacking csv.reader() Rows with Blank Lines or Inconsistent Column Counts

When reading CSV files with for uid, name, role in csv.reader(f):, real-world files almost always contain blank trailing lines or ragged rows:

  • Blank Lines (\n\n): Unlike "".split(",") (which returns ['']), csv.reader() yields an empty list [] on blank lines, crashing immediately with ValueError: not enough values to unpack (expected 3, got 0).
  • Short / Truncated Rows ("102,Bob"): Yields ['102', 'Bob'] -> ValueError: not enough values to unpack (expected 3, got 2).
  • Extra Unquoted Commas ("103,Charlie,editor,extra"): Yields 4 fields -> ValueError: too many values to unpack (expected 3).
  • The Trigger (Verified 3.10.16):
import csv, io

raw_csv = "101,Alice,admin\n\n102,Bob\n103,Charlie,editor,extra_col\n"
reader = csv.reader(io.StringIO(raw_csv))

for uid, name, role in reader:
    print(uid, name, role)
# Crashes on row 2 (blank line): ValueError: not enough values to unpack (expected 3, got 0)
  • The Fix: Iterate over row as a single list variable first, skip empty rows (if not row: continue), and check len(row) == 3 before unpacking (or use csv.DictReader to access columns by header name):
import csv, io

raw_csv = "101,Alice,admin\n\n102,Bob\n103,Charlie,editor,extra_col\n"
reader = csv.reader(io.StringIO(raw_csv))

for row_num, row in enumerate(reader, start=1):
    if not row:  # Skips blank lines ([])
        continue
    if len(row) != 3:
        print(f"Skipping malformed row {row_num} (got {len(row)} cols): {row!r}")
        continue
    uid, name, role = row
    print(f"Row {row_num} OK: {uid} | {name} | {role}")
# Verified Output:
# Row 1 OK: 101 | Alice | admin
# Skipping malformed row 3 (got 2 cols): ['102', 'Bob']
# Skipping malformed row 4 (got 4 cols): ['103', 'Charlie', 'editor', 'extra_col']

3. Looping Over a Dictionary Without .items() (And the Silent 2-Character Key Trap!)

When you write for k, v in user: without calling .items(), Python iterates over the dictionary’s keys. Because each key is usually a str (and strings are iterable sequences of characters!), Python tries to unpack the characters of the key string into k and v.

Watch what happens on a realistic dictionary user = {"id": 101, "role": "admin"}:

  1. First iteration ("id" — 2 characters): Because "id" has exactly 2 characters, k, v = "id" does NOT raise an error—it silently sets k = 'i' and v = 'd', completely ignoring the value 101!
  2. Second iteration ("role" — 4 characters): Unpacking "role" into k, v crashes with ValueError: too many values to unpack (expected 2).
  3. (And if a key has only 1 character, such as {"x": 10}, it crashes with ValueError: not enough values to unpack (expected 2, got 1).)
  • The Trigger (Verified 3.10.16):
user = {"id": 101, "role": "admin"}
for k, v in user:
    print(k, v)
# Iteration 1 silently prints: i d
# Iteration 2 crashes: ValueError: too many values to unpack (expected 2)
  • The Fix: Always call .items() when unpacking keys and values in a dictionary loop:
user = {"id": 101, "role": "admin"}
for k, v in user.items():
    print(k, v)  # Prints: id 101, then role admin

Can You Fix This Dictionary Loop Unpacking Error?

prices = {"apple": 1.50, "pear": 2.00}
for item, cost in prices:
    print(item, cost)

Why does this loop raise ValueError: too many values to unpack (expected 2), and how do you fix it?

4. Unpacking enumerate() Over a List of Tuples (for idx, x, y in enumerate(coords):)

When you have a list of 2-tuples coords = [(10, 20), (30, 40)] and wrap it in enumerate(coords), Python does not flatten the index and tuple into 3 items (0, 10, 20). Instead, enumerate() yields a nested 2-tuple (0, (10, 20)) where element 0 is the integer index and element 1 is the (x, y) tuple! Writing for idx, x, y in enumerate(coords): asks Python to unpack a 2-tuple into 3 variables.

  • The Trigger (Verified 3.10.16):
coords = [(10, 20), (30, 40)]
for idx, x, y in enumerate(coords):
    print(idx, x, y)
# ValueError: not enough values to unpack (expected 3, got 2)

The Fix: Wrap x, y in parentheses—for idx, (x, y) in enumerate(coords):—to match the nested (index, (x, y)) structure:

coords = [(10, 20), (30, 40)]
for idx, (x, y) in enumerate(coords):
    print(idx, x, y)  # Prints: 0 10 20, then 1 30 40

5. zip() Unpacking Mismatches & Catching Unequal Lengths with zip(..., strict=True)

Built-in zip() is involved in three frequent unpacking bugs:

  1. Passing a Single List of Pairs to zip(pairs) Without *: If pairs = [(1, 2), (3, 4)] and you write for x, y in zip(pairs):, zip() receives only one iterable argument and yields 1-tuples ((1, 2),), crashing with ValueError: not enough values to unpack (expected 2, got 1). Either loop over pairs directly (for x, y in pairs:) or unpack the list with * (xs, ys = zip(*pairs)) if you are transposing rows into columns.
  2. Unpacking zip() Across Sequences of Unequal Length: By default, zip(a, b) silently stops as soon as the shortest sequence ends. If users = ["Alice", "Bob", "Charlie"] (3 items) and scores = [95, 88] (2 items), zip(users, scores) only yields 2 pairs—so unpacking pair1, pair2, pair3 = zip(users, scores) crashes with ValueError: not enough values to unpack (expected 3, got 2), while a for u, s in zip(users, scores): loop silently drops "Charlie"!
  3. Detecting Length Mismatches Immediately with zip(..., strict=True) (Python 3.10+): Starting in Python 3.10 (PEP 618), pass strict=True whenever the zipped iterables are expected to have identical lengths. If one iterable finishes early, Python immediately raises a clear ValueError telling you which argument was shorter or longer:
  • The Trigger & Fix (Verified 3.10.16):
users = ["Alice", "Bob", "Charlie"]
scores = [95, 88]

# Trap 1: Unpacking 3 pairs when scores only has 2 items
# p1, p2, p3 = zip(users, scores)
# -> ValueError: not enough values to unpack (expected 3, got 2)

# Trap 2: Default zip() in a for-loop silently drops "Charlie"!
# Fix: Pass strict=True (Python 3.10+) to catch length mismatches immediately:
for user, score in zip(users, scores, strict=True):
    print(user, score)
# ValueError: zip() argument 2 is shorter than argument 1
  • 💡 If Unequal Lengths Are Intentional: Use itertools.zip_longest(users, scores, fillvalue=0) so shorter sequences are padded with a default value instead of truncated.

6. Unpacking Structured Library Return Tuples (urllib.parse.urlparse, os.stat, time.localtime)

Several standard library functions return NamedTuple-style structured objects with a fixed number of fields. For example, urllib.parse.urlparse() always returns a 6-element ParseResult tuple (scheme, netloc, path, params, query, fragment) (and urlsplit() returns a 5-tuple). Developers who assume urlparse() only returns (scheme, host, path) hit ValueError: too many values to unpack (expected 3).

  • The Trigger (Verified 3.10.16):
from urllib.parse import urlparse

url = "https://example.com/products?id=42"
# Fails: urlparse() returns 6 elements, not 3!
scheme, host, path = urlparse(url)
# ValueError: too many values to unpack (expected 3)
  • The Fix: Instead of positional unpacking, access the named attributes directly (.scheme, .netloc, .path, .query)—which is self-documenting and immune to tuple-length errors—or use *_ to ignore the remaining fields:
from urllib.parse import urlparse

parsed = urlparse("https://example.com/products?id=42")
print(parsed.scheme, parsed.netloc, parsed.path)
# Prints: https example.com /products

7. Unpacking an Already-Exhausted Generator, zip(), map(), or File Iterator (expected X, got 0)

Generators, zip(), map(), filter(), csv.reader(), and open file objects are single-pass iterators. Once you iterate over them—even implicitly by calling list(gen), sum(gen), or max(gen) for a debug print—the iterator is permanently exhausted. Attempting to unpack a, b = gen afterward yields 0 items and crashes with ValueError: not enough values to unpack (expected 2, got 0).

  • The Trigger (Verified 3.10.16):
gen = (x * 10 for x in range(2))
print("Debug check:", list(gen))  # Exhausts 'gen'!

first, second = gen
# ValueError: not enough values to unpack (expected 2, got 0)
  • The Fix: Materialize single-pass generators or zip() objects into a list or tuple once (items = list(gen)) if you need to inspect and unpack them multiple times:
items = [x * 10 for x in range(2)]
print("Debug check:", items)
first, second = items
print(first, second)  # Prints: 0 10

8. Safe Handling of Optional Values & Functions Returning Inconsistent Lengths

Functions that query a database, regex, or API often return a tuple on success (return "Alice", "admin", True), but return None, an empty tuple (), or a shorter tuple (return "Guest", "readonly") when a record is missing:

  • If the fallback branch returns ("Guest", "readonly") (2 items instead of 3) or (), unpacking name, role, active = fetch_user(2) raises ValueError: not enough values to unpack.
  • If the fallback branch returns None, unpacking raises TypeError: cannot unpack non-iterable NoneType object.
  • The Trigger (Verified 3.10.16):
def fetch_user(user_id: int):
    if user_id == 1:
        return "Alice", "admin", True
    return "Guest", "readonly"  # Bug: returns 2 values instead of 3!

name, role, is_active = fetch_user(2)
# ValueError: not enough values to unpack (expected 3, got 2)
  • The Fix (Keep Tuple Arity Consistent or Guard Optional Returns):
# Pattern 1: Keep the tuple arity identical across every return path
def fetch_user_consistent(user_id: int) -> tuple[str, str, bool]:
    if user_id == 1:
        return "Alice", "admin", True
    return "Guest", "readonly", False

# Pattern 2: If the function legitimately returns Optional (tuple | None),
# assign to a single variable first and guard with 'is not None' before unpacking:
def find_user_optional(user_id: int) -> tuple[str, str] | None:
    return ("Alice", "admin") if user_id == 1 else None

result = find_user_optional(2)
name, role = result if result is not None else ("Guest", "readonly")
print(name, role)  # Prints: Guest readonly

9. Unpacking sys.argv or Starred Targets (*rest) When Mandatory Elements Are Missing

Two command-line and slice patterns frequently fail when fewer arguments are passed than expected:

  1. script, input_path, output_path = sys.argv: Remember that sys.argv[0] is always the script filename. If a user runs python main.py without passing the two file paths, sys.argv only has 1 element (['main.py']), crashing with ValueError: not enough values to unpack (expected 3, got 1). Check if len(sys.argv) != 3: first or use argparse.
  2. Starred Unpacking (first, second, *rest = items): While *rest absorbs extra items (preventing too many values to unpack), it still requires at least 2 items for the mandatory targets first and second. Passing a 1-element list ["only_one"] raises ValueError: not enough values to unpack (expected at least 2, got 1).

10. Pandas DataFrame Iteration Traps (for idx, row in df: vs. iterrows() vs. itertuples())

In Pandas 2.0.0, two common loop mistakes trigger unpacking ValueError:

  1. Looping Directly Over df (for idx, row in df:): Just like a Python dict, iterating directly over a Pandas DataFrame yields its column name strings ("id", "name"), not its rows! On column "id" (2 characters), idx, row silently unpacks 'i' and 'd'; on column "name" (4 characters), it crashes with ValueError: too many values to unpack (expected 2)!
  2. Unpacking Columns Directly from df.iterrows() (for idx, uid, name in df.iterrows():): df.iterrows() always yields a 2-tuple (index, row_series). Unpacking 3 variables directly from iterrows() raises ValueError: not enough values to unpack (expected 3, got 2).
  • The Trigger (Verified Pandas 2.0.0):
import pandas as pd

df = pd.DataFrame({"id": [101, 102], "name": ["Alice", "Bob"]})

# Fails with: ValueError: not enough values to unpack (expected 3, got 2)
for idx, uid, name in df.iterrows():
    print(idx, uid, name)
  • The Fix (Choosing Between Vectorization, itertuples(), and iterrows()):
  • Best Performance: Avoid row loops altogether when a vectorized Pandas operation works (or use zip(df["id"], df["name"]) when you only need to iterate over a few columns).
  • When Iterating Rows with Unpacking (df.itertuples()): Use df.itertuples() (or df.itertuples(name=None) for plain tuples), which yields (Index, col1, col2, ...) directly and avoids the heavy overhead of constructing a pd.Series object on every row like df.iterrows() does:
import pandas as pd

df = pd.DataFrame({"id": [101, 102], "name": ["Alice", "Bob"]})

# Option 1 (Unpacks index + columns directly, much lower overhead than iterrows):
for idx, uid, name in df.itertuples():
    print(idx, uid, name)

# Option 2: Unpack the 2-tuple (idx, row) from iterrows()
for idx, row in df.iterrows():
    print(idx, row["id"], row["name"])

Comparing the 5 Unpacking & zip() Exceptions in Python

Python raises five distinct error messages during unpacking and parallel iteration depending on whether the right-hand side is non-iterable, too short, too long, or mismatched in zip(strict=True) (all verified on Python 3.10.16):

Assignment / Loop StatementRight-Hand Value (rhs)Exact Exception Raised (Verified 3.10.16)Root Cause
a, b = rhs["only_one"] (or [])ValueError: not enough values to unpack (expected 2, got 1)rhs is a valid iterable, but yielded fewer items than the 2 target variables.
a, b, *rest = rhs["only_one"]ValueError: not enough values to unpack (expected at least 2, got 1)Starred unpacking requires at least 2 items for the mandatory targets a and b.
a, b = rhs[1, 2, 3]ValueError: too many values to unpack (expected 2)rhs is a valid iterable, but yielded more than 2 items.
for x, y in zip(a, b, strict=True):a = [1, 2, 3], b = [10, 20]ValueError: zip() argument 2 is shorter than argument 1strict=True (Python 3.10+) caught two sequences of unequal length during iteration.
a, b = rhsNone (or 42)TypeError: cannot unpack non-iterable NoneType object (or int object)rhs is not an iterable at all (missing __iter__).

Catch Unbalanced Tuple Unpacking Before Runtime with Linters

Static analysis tools and type checkers catch mismatched tuple unpacking in your IDE before you run the script (not run by me; representative diagnostics noted from documentation—exact wording and error codes vary by tool version and configuration):

def get_coords() -> tuple[int, int]:
    return 10, 20

x, y, z = get_coords()  # <-- Flagged in IDE before runtime!
  • Pylint (E0632 unbalanced-tuple-unpacking): Enabled by default in Pylint; flags assignments where the number of target variables does not match the length of a tuple, list, or function return tuple (E0632: Possible unbalanced tuple unpacking with sequence: left side has 3 label(s), right side has 2 value(s)).
  • Mypy: Flags fixed-length tuple mismatches immediately (Need more than 2 values to unpack (3 expected) or Too many values to unpack (2 expected, 3 provided)).
  • Pyright / Pylance (VS Code): Flags tuple size mismatches under reportGeneralTypeIssues (Tuple size mismatch; expected 3 but received 2).
  • 💡 Type Annotation Tip: Annotate fixed-length tuple returns explicitly by position (-> tuple[str, int, bool]:) rather than variable-length -> tuple[Any, ...]: or -> list[Any]:. Fixed-length tuple annotations allow Mypy and Pylance to verify the exact target count at every call site!

Worked Example: Parsing KEY=VALUE Config Lines Without Unpacking Crashes

Let’s walk through a realistic bug where a simple configuration loader parses KEY=VALUE lines containing blank lines, # comments, and a database URL that has a second = inside its query string (?sslmode=require).

The Crashing Code (/var/www/app/main.py):

raw_env = """
DB_HOST=localhost
# Database connection string with '=' inside value
DB_URL=postgres://user:pass@localhost:5432/app?sslmode=require
"""

config = {}
for line in raw_env.splitlines():
    key, val = line.split("=")
    config[key] = val

Verified Traceback (Python 3.10.16):

Traceback (most recent call last):
  File "/var/www/app/main.py", line 9, in <module>
    key, val = line.split("=")
ValueError: not enough values to unpack (expected 2, got 1)

The Thought Process & Fix:

  1. Line 1 of raw_env is an empty string "", so "".split("=") returns [''] (1 item) and crashes with ValueError: not enough values to unpack (expected 2, got 1).
  2. Line 3 is a comment ("# Database connection...") with no "=", which would also return 1 item and crash with not enough values to unpack.
  3. Line 4 ("DB_URL=postgres://...?sslmode=require") contains two "=" characters, so .split("=") would return 3 items and crash with ValueError: too many values to unpack (expected 2).
  4. The Fix (Verified 3.10.16): Strip whitespace, skip blank and # comment lines, and use line.partition("=") while explicitly checking sep so lines missing "=" are either skipped (lenient) or rejected with a line-numbered ValueError (strict):
raw_env = """
DB_HOST=localhost
# Database connection string with '=' inside value
DB_URL=postgres://user:pass@localhost:5432/app?sslmode=require
"""

# Approach A (Lenient): Skip malformed lines where sep == ""
def parse_kv_optional(text: str) -> dict[str, str]:
    config = {}
    for raw_line in text.splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue
        key, sep, val = line.partition("=")
        if sep:  # Only store if '=' was actually present
            config[key.strip()] = val.strip()
    return config

# Approach B (Strict): Raise a line-numbered ValueError if '=' or key is missing
def parse_kv_strict(text: str) -> dict[str, str]:
    config = {}
    for line_no, raw_line in enumerate(text.splitlines(), start=1):
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue
        key, sep, val = line.partition("=")
        if not sep or not key.strip():
            raise ValueError(f"Line {line_no} is missing 'KEY=VALUE' format: {raw_line!r}")
        config[key.strip()] = val.strip()
    return config

print("Parsed:", parse_kv_strict(raw_env))
# Verified Output:
# Parsed: {'DB_HOST': 'localhost', 'DB_URL': 'postgres://user:pass@localhost:5432/app?sslmode=require'}
  1. ⚠️ Production .env Parser Note: The partition("=") parser above is great for simple KEY=VALUE text, but it intentionally does not handle shell-style .env features such as surrounding quotes (DB_PASS="my=secret"), inline comments (PORT=8080 # web port), export prefixes, escaped newlines (\n), or multiline values. For full .env specification support in production, use the python-dotenv library (dotenv_values(".env")).

Can You Fix This Pandas iterrows() Unpacking Error?

df = pd.DataFrame({"id": [101, 102], "name": ["Alice", "Bob"]})
for idx, uid, name in df.iterrows():
    print(idx, uid, name)

Why does this loop raise ValueError: not enough values to unpack (expected 3, got 2), and how do you unpack all 3 values cleanly?

Frequently Asked Questions

What is the difference between not enough values to unpack and too many values to unpack?

Both errors occur when unpacking an iterable into multiple variables (a, b = items). ValueError: not enough values to unpack (expected 2, got 1) means the right-hand side had fewer elements than variables on the left. ValueError: too many values to unpack (expected 2) means the right-hand side had more elements than variables on the left.

Why does too many values to unpack (expected 2) not tell me how many values it actually got?

During fixed-length unpacking into $N$ variables (a, b = iterator), Python pulls items one by one and stops the instant it sees the $(N + 1)$-th item. It does not consume the rest of the iterator just to count the remaining items (which also means a, b = itertools.count() fails immediately on the 3rd item instead of hanging—whereas starred unpacking a, b, *rest = itertools.count() will hang trying to fill rest!).

Why did csv.reader() raise ValueError: not enough values to unpack (expected 3, got 0)?

Unlike "".split(",") (which returns ['']), Python’s csv.reader() returns an empty list [] whenever it encounters a blank line in a CSV file. Always guard your loop with if not row: continue before unpacking a, b, c = row.

How do I catch unequal list lengths when unpacking zip() in a loop?

In Python 3.10+, pass strict=True (for a, b in zip(list1, list2, strict=True):). Without strict=True, zip() silently truncates to the shortest iterable; with strict=True, Python raises ValueError: zip() argument 2 is shorter/longer than argument 1 the moment one iterable ends before the other.

Why did for i, x, y in enumerate(coords): raise ValueError: not enough values to unpack (expected 3, got 2)?

enumerate() always returns a 2-tuple (index, item). When each item in coords is itself a (x, y) tuple, enumerate() yields (0, (10, 20))—which is a 2-element tuple whose second element is nested. Add parentheses around (x, y) in your loop header: for i, (x, y) in enumerate(coords):.

Similar Posts

Leave a Reply