โ† Back

Home โ€บ Errors โ€บ TypeError

TypeError: cannot unpack non-iterable NoneType object

Exception: TypeErrorCategory: runtime (unpacking)Raised at: the tuple-unpacking assignment whose right-hand side evaluated to None

What this error means

You unpacked a value into several variables, and that value was None. Unpacking needs something iterable to take the items from; None has nothing.

Traceback (most recent call last):
  File "demo.py", line 9, in <module>
    quotient, remainder = divide(10, 0)
TypeError: cannot unpack non-iterable NoneType object

The message is precise about the cause: non-iterable NoneType. Compare it with the sibling messages, which tell you a different story:

a, b = None            # ๐Ÿ’ฅ cannot unpack non-iterable NoneType object
a, b = 5               # ๐Ÿ’ฅ cannot unpack non-iterable int object
a, b = [1]             # ๐Ÿ’ฅ not enough values to unpack (expected 2, got 1)
a, b = [1, 2, 3]       # ๐Ÿ’ฅ too many values to unpack (expected 2)
a, b = [1, 2]          # โœ…

So this specific wording means the shape was never the problem โ€” there was no value at all. That points at a function that returned None on some code path.

The cause: a return path that returns nothing

A Python function that reaches the end of its body without hitting return gives back None. When the happy path returns a tuple but an early-exit path does not, only some calls break:

def divide(a, b):
    if b == 0:
        print("cannot divide by zero")   # โŒ no return here
    return a // b, a % b

divide(10, 2)        # โœ… (5, 0)
q, r = divide(10, 0) # ๐Ÿ’ฅ the b == 0 path returned None

# the fix: every path returns the same shape
def divide(a, b):
    if b == 0:
        return None, None                # โœ… same shape, explicit
    return a // b, a % b

# or raise instead โ€” usually better
import math

def divide(a, b):
    if b == 0:
        raise ZeroDivisionError("b must not be zero")
    return a // b, a % b

This is the whole bug in one example. The function *looks* like it returns a tuple, because the line at the bottom does. The early exit is what lies.

Other ways None gets unpacked

# 1 โ€” a dict lookup that missed
pair = users.get("missing")        # None
name, age = pair                   # ๐Ÿ’ฅ

# 2 โ€” re.match() on a non-match
import re
m = re.match(r"(\d+)-(\d+)", "abc")     # None
first, second = m.groups()              # ๐Ÿ’ฅ on None

m = re.match(r"(\d+)-(\d+)", "12-34")
if m:                                   # โœ… check first
    first, second = m.groups()

# 3 โ€” sort() and friends return None
nums = [3, 1, 2]
a, b, c = nums.sort()              # ๐Ÿ’ฅ sort() returns None
nums.sort(); a, b, c = nums        # โœ…

# 4 โ€” a variable only assigned inside a branch
result = None
if items:
    result = min(items), max(items)
lo, hi = result                    # ๐Ÿ’ฅ when items was empty

Cause 3 is the same trap as everywhere else with in-place methods: sort(), append() and reverse() return None by design. Capture the result and you capture None.

Finding which path failed

  1. Print the value before unpacking: result = f(...) then print(repr(result)). If it prints None, the function is the problem, not the unpacking.
  2. Open the function and read every return statement, plus the implicit end of the body. The bug is a path with no return, or a return with no value.
  3. Check for early exits: if ...: return, guard clauses, and except blocks that swallow an error and fall through.
  4. If the function is long, add assert result is not None at the call site temporarily โ€” it fails at the assignment rather than at the unpacking.
# a quick way to audit a function for missing returns
import ast, pathlib

src = pathlib.Path("mymodule.py").read_text()
for node in ast.walk(ast.parse(src)):
    if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
        rets = [n for n in ast.walk(node) if isinstance(n, ast.Return)]
        bare = [n for n in rets if n.value is None]
        if bare:
            print(f"{node.name}: bare 'return' at line {bare[0].lineno}")

The fixes

# 1 โ€” make every path return the same shape (best for expected cases)
def split_name(full):
    if not full:
        return "", ""
    parts = full.split(" ", 1)
    return parts[0], parts[1] if len(parts) > 1 else ""

# 2 โ€” raise instead (best when the case is genuinely an error)
def split_name(full):
    if not full:
        raise ValueError("full name is required")
    ...

# 3 โ€” return None and check before unpacking
result = divide(a, b)
if result is None:
    ...
else:
    q, r = result

# 4 โ€” unpack with a default using or
q, r = divide(a, b) or (None, None)

Option 4 is a stopgap, not a fix. It silences the crash but leaves the function lying about its return type, so the next caller hits the same None. Prefer making the producer honest.

Related messages worth knowing

๐Ÿ‡ฎ๐Ÿ‡ณ Hindi เคฎเฅ‡เค‚ เคธเคฎเคเฅ‡เค‚

TypeError: cannot unpack non-iterable NoneType object tab aata hai jab aap kisi value ko kai variables me unpack karte ho aur wo value None hoti hai. Unpacking ke liye kuch iterable chahiye; None ke paas kuch hai hi nahi. Message dhyan se padho โ€” non-iterable NoneType ka matlab hai shape ki problem thi hi nahi, value hi nahi thi. Ye seedha ishaara karta hai us function ki taraf jisne kisi code path par None return kar diya. Python me function jo bina return hit kiye body ke end tak pahunch jaata hai, wo None deta hai. Jab happy path tuple return karta hai lekin koi early-exit path nahi karta, to sirf kuch calls tootti hain โ€” aur wahi sabse confusing hai. Classic example: if b == 0: print(...) likh diya, return bhool gaye โ€” to sirf zero wale case par error aayega. Fix: har path same shape return kare, ya behtar ye ki error wale case me raise karo. Baaki wajah: dict.get() miss ho gaya; re.match() match na kare to None deta hai; sort() jaise in-place methods None return karte hain; aur variable sirf kisi branch ke andar assign hua. Debug karne ka tareeka: unpack karne se pehle print(repr(result)) lagao. None print hua to problem function me hai, unpacking me nahi. Phir function ke har return ko padho โ€” implicit end of body samet.

TypeError Hindi เคฎเฅ‡เค‚ เค เฅ€เค• เค•เคฐเคจเคพ เคธเฅ€เค–เฅ‡เค‚ โ†’