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
Nonein Python:- Built-in methods such as
list.sort(),list.reverse(),list.append(),list.extend(),dict.update(), andrandom.shuffle()mutate the container in place and returnNoneby 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.
- Built-in methods such as
dict.get("key", [])still returnsNoneif"key"exists with valueNone:- A classic trap with JSON APIs (
{"tags": None}) is writingdata.get("tags", [])—because"tags"is present indata,.get()ignores the default[]and returnsNone! Usedata.get("tags") or [](ortags = data.get("tags"); if tags is not None: ...) to handle both missing keys and explicitnullvalues safely.
- A classic trap with JSON APIs (
- 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. Ifget_coords()returnsNoneon an error path instead of raising an exception or returning a 2-tuple, Python raisesTypeError: cannot unpack non-iterable NoneType object(or'NoneType' object is not iterablein older versions).
- Unpacking (
- Functions with conditional branches missing a fallback
return:- If an
ifbranch returns a list (if valid: return results) while theelsepath falls off the end of the function without areturn, Python implicitly returnsNone. Always return an empty collection (return []) or raise an explicit exception on fallback paths.
- If an
- 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)):throwsTypeError: 'NoneType' object is not iterable, split the nested calls onto separate lines or inspectprint(type(obj), repr(obj))right before the loop to pinpoint which intermediate call returnedNone.
- When a complex line like
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. |
You must log in or register to comment.
