How do you fix "TypeError: 'NoneType' object is not iterable" in Python? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you fix ""TypeError: 'NoneType' object is not iterable"" in Python?

message-square
0

Inspect the variable or function call on the failing line that unexpectedly evaluated to None—most commonly from assigning the result of an in-place mutating method (list.sort(), list.append(), dict.update()), calling a function missing a return statement, or receiving None from dict.get() / regex / database lookups—and either remove the assignment on in-place methods, add an explicit return, or default None to an empty iterable (items or []).

Basic Example

# Common Cause 1: Assigning the return value of an in-place method (`sort()`, `append()`, `reverse()`)
nums = [3, 1, 2]
# wrong = nums.sort()      # Returns `None`! Iterating `for x in wrong:` raises TypeError
nums.sort()                # Mutates `nums` in place (or use `sorted_nums = sorted(nums)`)

# Common Cause 2: Function missing a `return` statement (implicitly returns `None`)
def get_active_users(users: list[str]) -> list[str]:
    active = [u for u in users if u.startswith("a")]
    return active          # Omitting `return active` makes the function return `None`

# 1. Recommended: Guard nullable collections with `or []` (or explicit `is not None` check)
api_response: dict[str, list[str] | None] = {"items": None}
for item in api_response.get("items") or []:
    print(item)

Key Details & Edge Cases

  • In-place mutating methods always return None in Python:
    • Built-in methods such as list.sort(), list.reverse(), list.append(), list.extend(), dict.update(), and random.shuffle() mutate the container in place and return None by design to prevent confusion between mutation and copying. Use functional equivalents (sorted(items), reversed(items), {**d1, **d2}) whenever you need to assign or iterate over the result directly.
  • dict.get("key", []) still returns None if "key" exists with value None:
    • A classic trap with JSON APIs ({"tags": None}) is writing data.get("tags", [])—because "tags" is present in data, .get() ignores the default [] and returns None! Use data.get("tags") or [] (or tags = data.get("tags"); if tags is not None: ...) to handle both missing keys and explicit null values safely.
  • Tuple unpacking fails with the exact same error (a, b = func()):
    • Unpacking (x, y = get_coords()) iterates over the right-hand side behind the scenes. If get_coords() returns None on an error path instead of raising an exception or returning a 2-tuple, Python raises TypeError: cannot unpack non-iterable NoneType object (or 'NoneType' object is not iterable in older versions).
  • Functions with conditional branches missing a fallback return:
    • If an if branch returns a list (if valid: return results) while the else path falls off the end of the function without a return, Python implicitly returns None. Always return an empty collection (return []) or raise an explicit exception on fallback paths.
  • Debugging multi-expression lines quickly (for x in a or b: / chained calls):
    • When a complex line like for row in fetch_rows(parse_config(path)): throws TypeError: 'NoneType' object is not iterable, split the nested calls onto separate lines or inspect print(type(obj), repr(obj)) right before the loop to pinpoint which intermediate call returned None.

Comparison of Common Causes & Fixes for 'NoneType' object is not iterable

Root Cause Broken Pattern Clean Fix Best Used When
In-place list/dict mutation assigned items = items.sort() items.sort() or items = sorted(items) Sorting, reversing, or updating lists/dicts before iterating.
JSON / Dict key has explicit None value for x in data.get("items", []): for x in data.get("items") or []: Consuming external JSON payloads or configs where keys may be null (None).
Function missing return on one branch def f(): if ok: return [1] Add return [] at the end of f() Writing helper functions that filter, query, or parse collections.
Failed search/regex/ORM query returning None for g in re.search(pat, s): if (m := re.search(pat, s)) is not None: ... Regex matches (re.search), BeautifulSoup .find(), or database .first() lookups.