How to Fix TypeError: ‘NoneType’ object is not iterable in Python

3D illustration for fixing NoneType object is not iterable error in Python.

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 as items.sort()) with ^^^^^^^^^^^^ carets so you can immediately see which call returned None.

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 crashing

3. 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 LikeRoot CauseThe 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

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):

  1. Primary Check (__iter__): Python checks whether type(obj) defines an __iter__(self) method returning an iterator. Standard containers (list, tuple, dict, set, str, range) implement __iter__().
  2. Legacy Sequence Fallback (__getitem__): If __iter__() is absent, iter(obj) checks whether type(obj) defines __getitem__(self, index) so it can iterate from index 0 upward until IndexError.
  3. Why None Fails: Python’s singleton None object (of class NoneType) represents the absence of a value and implements neither __iter__() nor __getitem__(). Calling iter(None) immediately raises TypeError: 'NoneType' object is not iterable.
  4. Definitive Runtime Check: While isinstance(obj, Iterable) checks for __iter__, calling iter(obj) inside a try / except TypeError block 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:

  1. Identify the exact failing line from the traceback: Look at the bottom frame of the traceback to see whether the crash happened in a for loop, a comprehension, a tuple unpacking line (a, b = ...), or a function call (list(), sum(), extend(), join()).
  2. 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)).
  3. Print type(rows).__name__ and repr(rows): Confirm right before the loop that rows is None.
  4. Check for in-place list/dict/DataFrame methods: Verify that rows was not assigned from .sort(), .reverse(), .append(), .extend(), dict.update(), or a Pandas method with inplace=True.
  5. Audit every return path in the producer function: Inspect the function that returned None. Look for an if block without a matching else, a bare return, or an except block that logs an error and returns nothing.
  6. Check external lookups (dict.get(), os.getenv(), database queries): If the value came from data.get("items", []), check whether "items" is explicitly present in data with a value of None (null in JSON).
  7. Fix the producer (or guard at the boundary): Make collection-returning functions return [] on empty paths, or guard optional external inputs with rows = [] 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 times

Can 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 sorts my_list and then tries to execute for x in None:.
  • If you write tags = tags.append("seo"), you overwrite your tags list variable with None, crashing the next loop that touches tags!
  • 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 use sorted(tags) / reversed(tags) inside the for header:
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 users vs. or []):
  1. Explicit is None Check (Recommended for Data Integrity): Writing users = payload.get("users"); users = [] if users is None else users only replaces None with []. If an upstream bug accidentally sends "users": 0 or "users": False, Python still raises a TypeError (or your isinstance(users, list) check catches it) so corrupted payloads aren’t silently ignored!
  2. The Limitation of payload.get("users") or []: While or [] is a popular shorthand, remember that or tests truthiness, not is None. It replaces every falsy value (None, [], (), "", 0, False, {}) with []. If a buggy API returns "users": 0 or "users": False, or [] silently masks the type bug by converting 0 or False into [], and if users was 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 check if 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 None

5. 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:

  1. Direct for Loop Over os.getenv() (for host in os.getenv("ALLOWED_HOSTS"):): When "ALLOWED_HOSTS" is unset, os.getenv() returns None and the loop crashes immediately with TypeError: '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 that os.getenv() always returns a str, not a list! If ALLOWED_HOSTS="localhost,example.com", looping directly over os.getenv() iterates character-by-character ('l', 'o', 'c'…) instead of host-by-host! Always .split(",") and filter out empty strings.
  2. Membership Test in on os.getenv() (if "admin" in os.getenv("ALLOWED_ROLES"):): When "ALLOWED_ROLES" is unset, testing in None raises TypeError: 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): Raises TypeError: 'NoneType' object is not iterable.
  • sum(None), max(None), min(None), sorted(None), any(None), all(None): Raises TypeError: 'NoneType' object is not iterable.
  • enumerate(None), zip(a, None), map(fn, None), filter(fn, None): Raises TypeError: 'NoneType' object is not iterable immediately upon construction.
  • my_list.extend(None) or my_list += None: Raises TypeError: 'NoneType' object is not iterable.
  • yield from None (inside a generator): Raises TypeError: 'NoneType' object is not iterable.
  • ", ".join(None): Raises TypeError: can only join an iterable.
  • [1, *None] (star-unpacking in a list/tuple): Raises TypeError: 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:

  1. Reassigning s = s.dropna(inplace=True) or df = df.dropna(inplace=True): Because inplace=True modifies the Series or DataFrame in place and returns None, reassigning the variable turns s or df into None. Looping directly over the Series (for val in s:) or DataFrame (for col in df: or list(df)) immediately raises TypeError: 'NoneType' object is not iterable. 💡 Note on df.iterrows(): If you instead call for _, row in df.iterrows(): when df is None, Python evaluates the .iterrows dot lookup before starting the loop, raising AttributeError: 'NoneType' object has no attribute 'iterrows'.
  2. 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 as sublist hits None!
  • 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 out None / 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 PatternWhen to Use ItExample Use CaseCaller 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 / RuntimeErrorWhen 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 xWhen x = NoneWhen x = [] or ()When x = “”When x = {}
for item in x:TypeError: 'NoneType' object is not iterableSucceeds (runs 0 times)Succeeds (runs 0 times)Succeeds (runs 0 times)
"a" in xTypeError: argument of type 'NoneType' is not iterableSucceeds: returns FalseSucceeds: returns FalseSucceeds: returns False
list(x)TypeError: 'NoneType' object is not iterableSucceeds: returns []Succeeds: returns []Succeeds: returns []
sum(x)TypeError: 'NoneType' object is not iterableSucceeds: returns 0TypeError (int + str)Succeeds: returns 0
[*x]TypeError: Value after * must be an iterable, not NoneTypeSucceeds: returns []Succeeds: returns []Succeeds: returns []
a, b = xTypeError: cannot unpack non-iterable NoneType objectValueError: 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 iterableiter(x) (__iter__()), which NoneType does not define.
x[0], x["key"], or x[:5] (Square brackets)TypeError: 'NoneType' object is not subscriptablex.__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 ItThe Fix
TypeError: cannot unpack non-iterable NoneType objectMultiple 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 iterableUsing 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 iterablePassing 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 NoneTypeStar-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 NoneTypeStar-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 iterableLooping 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 iterableLooping 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 | None under rule reportOptionalIterable (e.g., Object of type "None" cannot be used as iterable / is not iterable), and flags missing return paths under reportReturnType.
  • Pylint (E1133 not-an-iterable): Flags iterating over a value inferred as None (such as for 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 iterable

The Thought Process & Fix:

  1. In get_order_items(), when data.get("status") is "pending", the if condition is False. Because there is no else or final return statement, the function falls off the bottom and implicitly returns None.
  2. Even if "status" were "paid", the JSON contains "orders": null (None in Python). Because the key "orders" exists in data, data.get("orders", []) would still return None!
  3. The Result: Fix both traps without silently masking corrupted non-list data. In the optional approach, return [] when "orders" is missing or None, but still raise a TypeError if "orders" is a malformed non-list value like 123:
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

Why did my function return 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.

Why did 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 = ....

Why did 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.

Why did 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()].

What causes 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.

What causes 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:.

Similar Posts

Leave a Reply