
In Python, an iterable is any collection or sequence that can yield its elements one at a time—such as a list, tuple, dict, set, str, or generator. When a variable or function call unexpectedly evaluates to None (whose type is NoneType) and you try to loop over it (for x in items:), unpack it (a, b = pair), or pass it into a function that expects a collection (list(x), sum(x), ", ".join(x)), Python immediately halts with TypeError: 'NoneType' object is not iterable.
You almost never write for x in None: intentionally. Instead, this crash happens because a function fell off the end of an if block without a return statement, an in-place method like my_list.sort() or s.dropna(inplace=True) returned None, an environment variable lookup (os.getenv()) returned None, or a JSON dictionary lookup like data.get("users", []) hit an explicit null value.
Reading the 'NoneType' object is not iterable Traceback
Read the traceback from the bottom up. Python raises this error at the exact moment it calls iter(obj) on the target expression and discovers that obj is None:
Traceback (most recent call last):
File "/var/www/app/main.py", line 2, in <module>
for item in items.sort():
TypeError: 'NoneType' object is not iterable- Python 3.11+ Carets: Starting in Python 3.11+ (not run by me; noted from documentation), the traceback underlines the exact expression after
in(such asitems.sort()) with^^^^^^^^^^^^carets so you can immediately see which call returnedNone.
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: Return Empty Collections, Avoid In-Place Chaining, and Guard None
Choose the fix that matches where your None value originated:
1. Looping Over .sort(), .reverse(), or .append(): Use sorted() or Split the Line In-place list methods (list.sort(), list.reverse(), list.append(), list.extend()) mutate the list in memory and always return None. Use built-in sorted() or call .sort() on its own line before the loop:
items = ["banana", "apple", "cherry"]
# Fails: items.sort() sorts in-place and returns None!
# for item in items.sort():
# Fix 1: Use built-in sorted(), which returns a new sorted list
for item in sorted(items):
print(item)
# Fix 2: Sort in-place first, then loop over 'items' on the next line
items.sort()
for item in items:
print(item)2. Functions Missing a return on Empty Branches: Return [] Across Every Path If a function returns a list when matches exist, never let it fall off the end (or return None) when no matches are found. Return an empty list [] so the caller’s for loop safely runs zero times:
def get_even_numbers(nums):
evens = [n for n in nums if n % 2 == 0]
if not evens:
return [] # Safe fallback: always return an iterable list, never None
return evens
for n in get_even_numbers([1, 3, 5]):
print(n) # Loop safely runs 0 times without crashing3. Optional vs. Required External Data (dict.get() on JSON null): When a JSON payload contains "users": null, payload.get("users", []) returns None because the key exists! Check explicitly for None (so you don’t mask malformed non-list values like integers or booleans), or require a list when the field is mandatory:
payload = {"users": None}
# Optional list: Default None to [], but still fail if "users" is a corrupted type (e.g., 123)
users = payload.get("users")
for user in ([] if users is None else users):
print(user)
# Required list: Validate and fail fast with context
def get_required_users(data):
users = data.get("users")
if not isinstance(users, list):
raise ValueError(f"Expected 'users' to be a list, got: {users!r}")
return users⏱️ The 10-Second Diagnostic: What Your TypeError: 'NoneType' object is not iterable Looks Like
Find the pattern that matches your crashing line to grab the exact fix in under 15 seconds:
| What the Code Looks Like | Root Cause | The Exact Fix |
|---|---|---|
| for x in items.sort(): (or items = items.append(x)) | In-place list methods modify the list and return None. | Use for x in sorted(items): or call items.sort() before the loop. |
| for x in get_items(): (custom function) | Function is missing a return statement on one of its branches. | Return an empty list return [] on empty/fallback branches. |
| for u in data.get(“users”, []): (when data = {“users”: None}) | dict.get() returns None when the key exists with value None. | Check [] if u is None else u (or data.get(“users”) or []). |
| a, b = parse_line(text) (cannot unpack non-iterable NoneType) | Function returned None instead of a 2-tuple when parsing failed. | Return None, None on failure, or check if res is not None: before unpacking. |
| for h in os.getenv(“HOSTS”): (or if “admin” in os.getenv(“ROLES”):) | os.getenv() returns None when the environment variable is unset. | Default and split: [h for h in os.getenv(“HOSTS”, “”).split(“,”) if h] |
| list(val) / sum(val) / set(val) | Passed val = None into a built-in iterable consumer. | Guard before calling: list([] if val is None else val) |
| s = s.dropna(inplace=True) followed by for val in s: (or for col in df:) | Pandas inplace=True returns None, overwriting s or df. | Remove inplace=True: s = s.dropna() |
Can You Fix This In-Place .sort() Loop?
items = ["banana", "apple", "cherry"] for item in items.sort(): print(item)
Choose the best fix:
Table of contents
- Reading the ‘NoneType’ object is not iterable Traceback
- ⚡ The Quick Fix: Return Empty Collections, Avoid In-Place Chaining, and Guard None
- How Python Determines Iterability & Debugging Workflow
- Common Causes of TypeError: ‘NoneType’ object is not iterable
- 1. Functions Missing a return Statement on One Branch (Implicit None )
- Can You Fix This Missing return Statement Bug?
- 2. Iterating Over In-Place List Methods ( .sort() , .reverse() , .append() , .extend() )
- 3. The dict.get(“users”, []) Trap When a JSON Key Is null (And the Limitations of or [] )
- 4. Unpacking None into Multiple Variables ( TypeError: cannot unpack non-iterable NoneType object )
- 5. Looping Over or Checking in on os.getenv() / os.environ.get()
- 6. Passing None to Built-In Iterable Consumers ( list() , sum() , str.join() , yield from , *None )
- 7. Pandas inplace=True & DataFrame Columns Containing None Lists
- Design Guide: When Should a Function return [] vs. return None ?
- None vs. Empty Iterables ( [] , () , “” , {} ): Why Only None Crashes
- The Three ‘NoneType’ Errors Compared ( not iterable vs. not subscriptable vs. has no attribute )
- Sibling Non-Iterable TypeError Variants
- Catch Non-Iterable None Bugs Before Runtime with Type Checkers
- Worked Example: Fixing a Multi-Branch Order Webhook Processor
- Frequently Asked Questions
- Official Documentation & Related Fixes
How Python Determines Iterability & Debugging Workflow
How Python Determines Whether an Object Is Iterable
Whenever you run for x in obj:, unpack a, b = obj, or call list(obj), CPython invokes the built-in iter(obj) function (PyObject_GetIter in C):
- Primary Check (
__iter__): Python checks whethertype(obj)defines an__iter__(self)method returning an iterator. Standard containers (list,tuple,dict,set,str,range) implement__iter__(). - Legacy Sequence Fallback (
__getitem__): If__iter__()is absent,iter(obj)checks whethertype(obj)defines__getitem__(self, index)so it can iterate from index0upward untilIndexError. - Why
NoneFails: Python’s singletonNoneobject (of classNoneType) represents the absence of a value and implements neither__iter__()nor__getitem__(). Callingiter(None)immediately raisesTypeError: 'NoneType' object is not iterable. - Definitive Runtime Check: While
isinstance(obj, Iterable)checks for__iter__, callingiter(obj)inside atry / except TypeErrorblock is the only universal test that covers both__iter__()and legacy__getitem__()sequences:
def is_iterable(obj):
try:
iter(obj)
return True
except TypeError:
return False
records = None
print(f"Type: {type(records).__name__} | Value: {records!r} | Iterable: {is_iterable(records)}")Verified Output (Python 3.10.16):
Type: NoneType | Value: None | Iterable: False
Step-by-Step Debugging Workflow
When TypeError: 'NoneType' object is not iterable crashes your script, follow this 7-step workflow to find and fix the exact source of None:
- Identify the exact failing line from the traceback: Look at the bottom frame of the traceback to see whether the crash happened in a
forloop, a comprehension, a tuple unpacking line (a, b = ...), or a function call (list(),sum(),extend(),join()). - Isolate the target expression: If the line calls a function or method directly inside the loop header (
for row in fetch_rows(client):), assign it to a temporary variable on the line above (rows = fetch_rows(client)). - Print
type(rows).__name__andrepr(rows): Confirm right before the loop thatrowsisNone. - Check for in-place list/dict/DataFrame methods: Verify that
rowswas not assigned from.sort(),.reverse(),.append(),.extend(),dict.update(), or a Pandas method withinplace=True. - Audit every
returnpath in the producer function: Inspect the function that returnedNone. Look for anifblock without a matchingelse, a barereturn, or anexceptblock that logs an error and returns nothing. - Check external lookups (
dict.get(),os.getenv(), database queries): If the value came fromdata.get("items", []), check whether"items"is explicitly present indatawith a value ofNone(nullin JSON). - Fix the producer (or guard at the boundary): Make collection-returning functions return
[]on empty paths, or guard optional external inputs withrows = [] if raw_rows is None else raw_rows.
Common Causes of TypeError: 'NoneType' object is not iterable
Here are the seven most frequent ways None sneaks into a loop, unpacking assignment, or collection consumer.
1. Functions Missing a return Statement on One Branch (Implicit None)
In Python, any function that reaches the end of its body without executing an explicit return value statement automatically returns None. A classic bug is writing a function that returns a list inside an if block (or try block), but forgets to return an empty list [] when the if condition is False (or when an exception is caught in except).
- The Trigger (Verified 3.10.16):
def get_even_numbers(nums):
evens = [n for n in nums if n % 2 == 0]
if evens:
return evens
# Bug: implicitly returns None when 'evens' is empty!
for n in get_even_numbers([1, 3, 5]):
print(n)
# TypeError: 'NoneType' object is not iterable- The Fix: Ensure every execution path in a collection-returning function explicitly returns an iterable (such as
return []) or raises an exception:
def get_even_numbers(nums):
return [n for n in nums if n % 2 == 0] # Returns [] when no evens match
for n in get_even_numbers([1, 3, 5]):
print(n) # Safely runs 0 timesCan You Fix This Missing return Statement Bug?
def get_admins(users): if users: return [u for u in users if u.get("is_admin")] for admin in get_admins([]): print(admin)
What should get_admins() return when users is empty so the loop doesn’t crash?
2. Iterating Over In-Place List Methods (.sort(), .reverse(), .append(), .extend())
In Python, methods that mutate a list in place—including list.sort(), list.reverse(), list.append(), list.extend(), list.insert(), and list.remove()—always return None.
- If you write
for x in my_list.sort():, Python sortsmy_listand then tries to executefor x in None:. - If you write
tags = tags.append("seo"), you overwrite yourtagslist variable withNone, crashing the next loop that touchestags! - The Trigger (Verified 3.10.16):
tags = ["python", "debugging"]
tags = tags.append("seo") # Overwrites 'tags' with None!
for tag in tags:
print(tag)
# TypeError: 'NoneType' object is not iterable- The Fix: Call
.append(),.extend(), or.sort()on its own line without reassigning the variable back to itself, or usesorted(tags)/reversed(tags)inside theforheader:
tags = ["python", "debugging"]
tags.append("seo") # Mutates 'tags' in place
for tag in sorted(tags):
print(tag)3. The dict.get("users", []) Trap When a JSON Key Is null (And the Limitations of or [])
When consuming REST APIs or webhooks, developers often write for u in payload.get("users", []): assuming the fallback [] guarantees a list. However, dict.get(key, default) only returns default when key is completely missing from the dictionary. If the JSON payload contains {"users": null}, json.loads() parses that into {"users": None}. Because the "users" key exists, payload.get("users", []) returns None instead of []!
- The Trigger (Verified 3.10.16):
payload = {"users": None}
# The key "users" exists, so .get("users", []) returns None!
for user in payload.get("users", []):
print(user)
# TypeError: 'NoneType' object is not iterable- The Fix (
[] if users is None else usersvs.or []):
- Explicit
is NoneCheck (Recommended for Data Integrity): Writingusers = payload.get("users"); users = [] if users is None else usersonly replacesNonewith[]. If an upstream bug accidentally sends"users": 0or"users": False, Python still raises aTypeError(or yourisinstance(users, list)check catches it) so corrupted payloads aren’t silently ignored! - The Limitation of
payload.get("users") or []: Whileor []is a popular shorthand, remember thatortests truthiness, notis None. It replaces every falsy value (None,[],(),"",0,False,{}) with[]. If a buggy API returns"users": 0or"users": False,or []silently masks the type bug by converting0orFalseinto[], and ifuserswas an empty tuple(), it allocates a new list unnecessarily.
payload = {"users": None}
# Fix 1 (Recommended — only defaults None, does not mask 0 or False):
users = payload.get("users")
for user in ([] if users is None else users):
print(user)
# Fix 2 (Shorthand falsy coalescing — replaces any falsy value with []):
for user in (payload.get("users") or []):
print(user)4. Unpacking None into Multiple Variables (TypeError: cannot unpack non-iterable NoneType object)
Multiple assignment (tuple unpacking) like key, val = parse_pair(line) or status, body = fetch_data() is an iteration operation under the hood. When a function returns a tuple (a, b) on success but returns None (either explicitly or implicitly) on failure, unpacking None into two variables raises TypeError: cannot unpack non-iterable NoneType object.
- The Trigger (Verified 3.10.16):
def parse_pair(text):
if ":" in text:
return text.split(":", 1)
return None # Bug: caller tries to unpack None into 2 variables!
key, val = parse_pair("invalid_line")
# TypeError: cannot unpack non-iterable NoneType object- The Fix: Either return a tuple of
Nones matching the expected length (return None, None), or assign the result to a single variable first and checkif result is not None:before unpacking:
def parse_pair(text):
if ":" in text:
return text.split(":", 1)
return None, None # Safe: matches 2-variable unpacking signature
key, val = parse_pair("invalid_line")
print(key, val) # Prints: None None5. Looping Over or Checking in on os.getenv() / os.environ.get()
Environment variable lookups (os.getenv("VAR") and os.environ.get("VAR")) return None whenever the variable is not set in your shell, .env, or Docker container. That triggers two distinct NoneType iteration errors—plus a sneaky string-iteration trap:
- Direct
forLoop Overos.getenv()(for host in os.getenv("ALLOWED_HOSTS"):): When"ALLOWED_HOSTS"is unset,os.getenv()returnsNoneand the loop crashes immediately withTypeError: 'NoneType' object is not iterable. ⚠️ The String-Iteration Trap: Even if you add an empty string default (for host in os.getenv("ALLOWED_HOSTS", ""):), remember thatos.getenv()always returns astr, not alist! IfALLOWED_HOSTS="localhost,example.com", looping directly overos.getenv()iterates character-by-character ('l','o','c'…) instead of host-by-host! Always.split(",")and filter out empty strings. - Membership Test
inonos.getenv()(if "admin" in os.getenv("ALLOWED_ROLES"):): When"ALLOWED_ROLES"is unset, testingin NoneraisesTypeError: argument of type 'NoneType' is not iterable.
- The Trigger (Verified 3.10.16):
import os
# Crash 1: Direct for-loop when ALLOWED_HOSTS is unset
for host in os.getenv("ALLOWED_HOSTS"):
print(host)
# TypeError: 'NoneType' object is not iterable
# Crash 2: Membership test 'in' when ALLOWED_ROLES is unset
if "admin" in os.getenv("ALLOWED_ROLES"):
print("Granted")
# TypeError: argument of type 'NoneType' is not iterable- The Fix: Default
os.getenv("VAR", "")to an empty string,.split(",")into a list of items, and strip/filter out blank entries so unset variables cleanly become[]:
import os
# Safe list loop over a comma-separated environment variable:
raw_hosts = os.getenv("ALLOWED_HOSTS", "")
hosts = [h.strip() for h in raw_hosts.split(",") if h.strip()]
for host in hosts:
print(host)
# Safe membership test:
raw_roles = os.getenv("ALLOWED_ROLES", "")
roles = {r.strip() for r in raw_roles.split(",") if r.strip()}
if "admin" in roles:
print("Granted")6. Passing None to Built-In Iterable Consumers (list(), sum(), str.join(), yield from, *None)
Passing a None variable into any built-in function or syntax construct that consumes an iterable will immediately crash:
list(None),tuple(None),set(None),dict(None): RaisesTypeError: 'NoneType' object is not iterable.sum(None),max(None),min(None),sorted(None),any(None),all(None): RaisesTypeError: 'NoneType' object is not iterable.enumerate(None),zip(a, None),map(fn, None),filter(fn, None): RaisesTypeError: 'NoneType' object is not iterableimmediately upon construction.my_list.extend(None)ormy_list += None: RaisesTypeError: 'NoneType' object is not iterable.yield from None(inside a generator): RaisesTypeError: 'NoneType' object is not iterable.", ".join(None): RaisesTypeError: can only join an iterable.[1, *None](star-unpacking in a list/tuple): RaisesTypeError: Value after * must be an iterable, not NoneType.
7. Pandas inplace=True & DataFrame Columns Containing None Lists
In Pandas 2.0.0, two distinct patterns trigger TypeError: 'NoneType' object is not iterable:
- Reassigning
s = s.dropna(inplace=True)ordf = df.dropna(inplace=True): Becauseinplace=Truemodifies the Series or DataFrame in place and returnsNone, reassigning the variable turnssordfintoNone. Looping directly over the Series (for val in s:) or DataFrame (for col in df:orlist(df)) immediately raisesTypeError: 'NoneType' object is not iterable. 💡 Note ondf.iterrows(): If you instead callfor _, row in df.iterrows():whendfisNone, Python evaluates the.iterrowsdot lookup before starting the loop, raisingAttributeError: 'NoneType' object has no attribute 'iterrows'. - Iterating Over a Column of Lists That Contains
None(NaN) Cells: When a DataFrame column stores lists (e.g.,[["python", "seo"], None]) and you flatten it with a nested list comprehension[t for sublist in df["tags"] for t in sublist], the inner loop crashes as soon assublisthitsNone!
- The Trigger (Verified Pandas 2.0.0):
import pandas as pd
# Trigger A: Reassigning inplace=True and looping directly over the Series/DataFrame
s = pd.Series([10.0, None, 30.0])
s = s.dropna(inplace=True) # s is now None!
# for val in s: # TypeError: 'NoneType' object is not iterable
# Trigger B: Nested comprehension over a column containing a None cell
df = pd.DataFrame({"tags": [["python", "seo"], None]})
all_tags = [t for sublist in df["tags"] for t in sublist]
# TypeError: 'NoneType' object is not iterable- The Fix: Remove
inplace=True(s = s.dropna()), and filter outNone/ non-list cells in nested comprehensions (if isinstance(sublist, list)):
import pandas as pd
s = pd.Series([10.0, None, 30.0]).dropna()
df = pd.DataFrame({"tags": [["python", "seo"], None]})
all_tags = [t for sublist in df["tags"] if isinstance(sublist, list) for t in sublist]
print(list(s), "|", all_tags) # [10.0, 30.0] | ['python', 'seo']Design Guide: When Should a Function return [] vs. return None?
Choosing the right return contract in your own functions prevents TypeError: 'NoneType' object is not iterable across your entire codebase:
| Return Pattern | When to Use It | Example Use Case | Caller Ergonomics |
return [] (Empty Collection / Null Object Pattern) | Whenever a function searches, filters, or queries for multiple items and finding 0 matches is a normal, valid outcome. | get_active_users(), filter_even_numbers(), parse_csv_rows() | Callers can loop immediately (for u in get_active_users():) with zero if is not None: boilerplate. |
return None (Typed as list[T] | None) | Only when “no collection exists / not initialized / cache miss” means something different in your domain than “the collection exists and has 0 items”. | A cache lookup where None means cache miss (query the DB) and [] means cached empty result; or a PATCH payload where tags=None means leave unchanged and tags=[] means clear all tags. | Callers must check if items is not None: before iterating (enforced by Mypy and Pyright). |
raise ValueError / RuntimeError | When an input is invalid, a required resource is missing, or a database/API call failed. | Failed HTTP request, invalid user_id <= 0, or corrupted JSON schema. | Fails fast at the source instead of passing a silent None downstream into a loop. |
None vs. Empty Iterables ([], (), "", {}): Why Only None Crashes
Beginners often treat None and an empty list [] as interchangeable because both evaluate to False in a boolean check (if not items:). However, in any iteration context, empty containers succeed cleanly while None crashes:
| Operation on x | When x = None | When x = [] or () | When x = “” | When x = {} |
for item in x: | TypeError: 'NoneType' object is not iterable | Succeeds (runs 0 times) | Succeeds (runs 0 times) | Succeeds (runs 0 times) |
"a" in x | TypeError: argument of type 'NoneType' is not iterable | Succeeds: returns False | Succeeds: returns False | Succeeds: returns False |
list(x) | TypeError: 'NoneType' object is not iterable | Succeeds: returns [] | Succeeds: returns [] | Succeeds: returns [] |
sum(x) | TypeError: 'NoneType' object is not iterable | Succeeds: returns 0 | TypeError (int + str) | Succeeds: returns 0 |
[*x] | TypeError: Value after * must be an iterable, not NoneType | Succeeds: returns [] | Succeeds: returns [] | Succeeds: returns [] |
a, b = x | TypeError: cannot unpack non-iterable NoneType object | ValueError: not enough values to unpack (expected 2, got 0) | ValueError: not enough values to unpack (expected 2, got 0) | ValueError: not enough values to unpack (expected 2, got 0) |
💡 Notice the Unpacking Row (a, b = x): Unpacking None raises a TypeError (cannot unpack non-iterable NoneType object) because None cannot be iterated at all. Unpacking an empty list [] raises a ValueError (not enough values to unpack) because [] is a valid iterable that simply had 0 items instead of 2!
The Three 'NoneType' Errors Compared (not iterable vs. not subscriptable vs. has no attribute)
All three of Python’s NoneType exceptions happen because a variable evaluated to None, but the operation you attempted on that variable determines which error message appears:
| Operation on x (when x = None) | Exact Exception Raised (Verified 3.10.16) | What Python Tried to Call on None |
for i in x:, list(x), or a, b = x (Iteration) | TypeError: 'NoneType' object is not iterable | iter(x) (__iter__()), which NoneType does not define. |
x[0], x["key"], or x[:5] (Square brackets) | TypeError: 'NoneType' object is not subscriptable | x.__getitem__(), which NoneType does not define. |
x.strip(), x.get("k"), or x.iterrows() (Dot access) | AttributeError: 'NoneType' object has no attribute '...' | Attribute lookup via __getattribute__(), which fails for any method name. |
Sibling Non-Iterable TypeError Variants
Depending on the exact syntax or scalar type that reached your loop or unpacking line, Python raises several closely related TypeError messages (all verified on Python 3.10.16):
| Error Message Variant (Verified 3.10.16) | What Triggered It | The Fix |
TypeError: cannot unpack non-iterable NoneType object | Multiple assignment from a function that returned None (a, b = func()). | Return None, None from the function on failure, or check if res is not None: before unpacking. |
TypeError: argument of type 'NoneType' is not iterable | Using in or not in when the right-hand operand is None ("admin" in roles). | Guard with if roles is not None and "admin" in roles:, or default roles to "" / (). |
TypeError: can only join an iterable | Passing None into str.join(), such as ", ".join(tags) when tags is None. | Guard None before joining: ", ".join([] if tags is None else tags). |
TypeError: Value after * must be an iterable, not NoneType | Star-unpacking None inside a list or tuple literal ([1, *extra_items]). | Guard inside the star unpack: [1, *([] if extra_items is None else extra_items)]. |
TypeError: fn() argument after * must be an iterable, not NoneType | Star-unpacking None in a function call (fn(*args) when args is None). | Guard with fn(*(() if args is None else args)). |
TypeError: 'int' object is not iterable | Looping over an integer (for i in len(items): or for i in 5:) or returning 0 instead of []. | Wrap counts in range(len(items)), and return [] instead of 0. |
TypeError: 'bool' object is not iterable | Looping over False or True (when a function returned False on error instead of []). | Return [] instead of False, or raise an exception on error. |
Catch Non-Iterable None Bugs Before Runtime with Type Checkers
Static type checkers (Mypy and Pyright / Pylance) and linters (Pylint) catch both missing return statements and unguarded Optional (list[T] | None) loops in your IDE before you run your code (not run by me; representative diagnostics noted from documentation—exact wording and error codes vary by tool version and strictness settings):
def fetch_tags(post_id: int) -> list[str] | None:
if post_id == 1:
return ["python", "debugging"]
return None
for tag in fetch_tags(2): # <-- Flagged in IDE before runtime!
print(tag)- Mypy: Flags iterating over a nullable union with
union-attr(e.g.,Item "None" of "list[str] | None" has no attribute "__iter__" (not iterable)), or flags missing return paths with[return]when a function is annotated as-> list[str]:. - Pyright / Pylance (VS Code): Flags unguarded loops over
T | Noneunder rulereportOptionalIterable(e.g.,Object of type "None" cannot be used as iterable/is not iterable), and flags missing return paths underreportReturnType. - Pylint (
E1133not-an-iterable): Flags iterating over a value inferred asNone(such asfor x in items.sort():).
Worked Example: Fixing a Multi-Branch Order Webhook Processor
Let’s walk through a realistic bug where an order-processing function crashes with TypeError: 'NoneType' object is not iterable for two separate reasons: an implicit None return on unpaid orders, and an explicit "orders": null field in the JSON payload.
The Crashing Code (/var/www/app/main.py):
import json
def get_order_items(raw_payload):
data = json.loads(raw_payload)
if data.get("status") == "paid":
return data.get("orders", [])
payload = '{"status": "pending", "orders": null}'
for order in get_order_items(payload):
print(order)Verified Traceback (Python 3.10.16):
Traceback (most recent call last):
File "/var/www/app/main.py", line 9, in <module>
for order in get_order_items(payload):
TypeError: 'NoneType' object is not iterableThe Thought Process & Fix:
- In
get_order_items(), whendata.get("status")is"pending", theifcondition isFalse. Because there is noelseor finalreturnstatement, the function falls off the bottom and implicitly returnsNone. - Even if
"status"were"paid", the JSON contains"orders": null(Nonein Python). Because the key"orders"exists indata,data.get("orders", [])would still returnNone! - The Result: Fix both traps without silently masking corrupted non-list data. In the optional approach, return
[]when"orders"is missing orNone, but still raise aTypeErrorif"orders"is a malformed non-list value like123:
import json
from typing import Any
# Approach A (Optional / Empty Allowed): Convert None -> [], but reject corrupted non-list types!
def get_order_items_optional(raw_payload: str) -> list[dict[str, Any]]:
data = json.loads(raw_payload)
if data.get("status") != "paid":
return []
orders = data.get("orders")
if orders is None:
return []
if not isinstance(orders, list):
raise TypeError(f"Expected 'orders' to be a list or null, got {type(orders).__name__}: {orders!r}")
return orders
# Approach B (Strict / Required): Require paid status and a valid list
def get_order_items_strict(raw_payload: str) -> list[dict[str, Any]]:
data = json.loads(raw_payload)
if data.get("status") != "paid":
raise ValueError(f"Cannot process unpaid order payload: status={data.get('status')!r}")
orders = data.get("orders")
if not isinstance(orders, list):
raise ValueError(f"Expected 'orders' to be a list, got: {orders!r}")
return orders
payload_pending = '{"status": "pending", "orders": null}'
payload_paid_null = '{"status": "paid", "orders": null}'
print("Optional pending: ", get_order_items_optional(payload_pending))
print("Optional paid null:", get_order_items_optional(payload_paid_null))
# Verified Output:
# Optional pending: []
# Optional paid null: []Can You Fix This JSON null Loop?
payload = {"users": None} for user in payload.get("users", []): print(user)
Choose the best fix when "users" is explicitly None:
Frequently Asked Questions
None when I didn’t write return None?In Python, any function that finishes executing without hitting an explicit return value statement—or that hits a bare return statement—automatically returns None. Check your function for if / elif blocks without an else branch, or try / except blocks where the except branch logs an error without returning [] or re-raising.
for x in my_list.sort(): or my_list = my_list.append(item) raise TypeError: 'NoneType' object is not iterable?List mutation methods (.sort(), .reverse(), .append(), .extend()) modify the existing list in place and intentionally return None. Use for x in sorted(my_list): to sort inside a loop header, and call my_list.append(item) on its own line without reassigning my_list = ....
for x in data.get("items", []): still crash with 'NoneType' object is not iterable?dict.get("items", []) only returns the fallback [] when the "items" key is absent from data. If "items" is present in data with a value of None (for example, "items": null in JSON), .get() returns None. Use items = data.get("items"); for x in ([] if items is None else items): (or for x in (data.get("items") or []):) to handle both missing keys and None values.
for host in os.getenv("ALLOWED_HOSTS"): crash when the variable was unset, and why did it loop over single letters when set?When "ALLOWED_HOSTS" is unset, os.getenv() returns None, raising TypeError: 'NoneType' object is not iterable. When it is set (e.g., "localhost,example.com"), os.getenv() returns a str, so a for loop iterates over individual characters ('l', 'o', 'c'…). Always provide a default empty string and split on commas: [h.strip() for h in os.getenv("ALLOWED_HOSTS", "").split(",") if h.strip()].
TypeError: cannot unpack non-iterable NoneType object?You wrote a multiple-assignment unpacking line like a, b = my_func(), and my_func() returned None instead of a 2-element tuple or list. Either update my_func() to return None, None on failure, or assign res = my_func() to a single variable and check if res is not None: before unpacking a, b = res.
TypeError: argument of type 'NoneType' is not iterable?You used the in or not in operator (if "x" in target:), and target evaluated to None. Guard the membership check with if target is not None and "x" in target:.
Official Documentation & Related Fixes
- Master Guide: The Ultimate Python Debugging Guide: Tracebacks, Exceptions, and Fixes
- Related Error: How to Fix TypeError: ‘int’ object is not iterable
- Related Error: How to Fix TypeError: ‘NoneType’ object is not subscriptable
- Related Error: How to Fix AttributeError: ‘NoneType’ object has no attribute ‘x’
- Official Python Docs: Built-in Functions — iter()
