
In Python, a subscriptable object is any container that implements the __getitem__() method so you can access its elements using square brackets []—such as a list (items[0]), dict (user["name"]), tuple, str, or Pandas DataFrame. When a variable unexpectedly evaluates to None (whose type is NoneType) and you try to index, slice, or look up a key on it with variable[...], Python immediately halts with TypeError: 'NoneType' object is not subscriptable.
In almost every case, you didn’t intend to index None. Instead, an in-place method like my_list.sort() or df.dropna(inplace=True), a database query (cursor.fetchone()), a regex search (re.search()), an HTML scraper (soup.find()), or a JSON key containing null silently returned None right before your square brackets ran.
Reading the 'NoneType' object is not subscriptable Traceback
Read the traceback from the bottom up. Python raises this error at the exact moment it attempts to evaluate obj[index], obj[key], or obj[start:stop] and discovers that obj is None:
Traceback (most recent call last):
File "/var/www/app/main.py", line 2, in <module>
lowest = scores.sort()[0]
TypeError: 'NoneType' object is not subscriptable- Python 3.11+ Carets: Starting in Python 3.11+ (not run by me; noted from documentation), the traceback draws
~~~~~~~~~~~~~^^^carets directly under the expression and the[0]brackets that failed, making it easy to see which bracketed lookup evaluated toNoneon lines with chained lookups likedata["user"]["profile"]["id"].
Tested Environment: Python 3.10.16, NumPy 1.26.3 & Pandas 2.0.0 (Linux) | Python 3.11+ carets, BeautifulSoup (
bs4), and linter/type-checker CLI outputs not run by me; noted from documentation.Part of: The Ultimate Python Debugging Guide
⚡ The Quick Fix: Stop Chaining In-Place Methods and Guard Against None
Choose the fix that matches where your None value originated:
1. Sorting or Modifying a List Before Indexing: Use sorted() or Split the Line In-place list methods (list.sort(), list.reverse(), list.append()) modify the list in memory and always return None. Never chain [0] onto .sort() or assign scores = scores.sort():
scores = [88, 95, 72] # Fails: scores.sort() returns None, so None[0] crashes! # lowest = scores.sort()[0] # Fix 1: Use built-in sorted(), which returns a new sorted list lowest = sorted(scores)[0] # Fix 2: Sort in-place first, then index on the next line scores.sort() lowest = scores[0] print(lowest) # Prints: 72
2. Optional Nested Dictionaries or Lists: Guard Against Explicit None Values When a key in a JSON payload is explicitly null ({"profile": None, "items": None}), data.get("profile", {}) and data.get("items", []) still return None because the keys exist! Guard against None explicitly with is not None (or coalesce with or {} / or []) before indexing:
data = {"id": 1042, "profile": None, "items": None}
# Safe Dict Guard (Explicit None check):
profile = data.get("profile")
country = profile.get("country", "Unknown") if profile is not None else "Unknown"
# Safe List Guard (Explicit None + non-empty check before indexing [0]):
items = data.get("items")
first_item = items[0] if items is not None and len(items) > 0 else None
print(country, "|", first_item) # Prints: Unknown | None3. Required Data: Validate and Raise a Meaningful Error When your business logic strictly requires a valid dictionary, non-empty list, or database record, do not silently fall back to None or "Unknown". Validate at the boundary and raise a descriptive error immediately:
def get_required_country(data):
profile = data.get("profile")
if not isinstance(profile, dict) or "country" not in profile:
raise ValueError(f"Expected a valid 'profile.country' dict, got: {profile!r}")
return profile["country"]⏱️ The 10-Second Diagnostic: What Your TypeError: 'NoneType' object is not subscriptable 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 |
|---|---|---|
| scores.sort()[0] (or scores.reverse()[0]) | In-place list methods modify the list and return None. | Use sorted(scores)[0] or slice scores[::-1][0] |
| data.get(“user”, {})[“city”] (or data.get(“items”, [])[0]) | dict.get() returns None when the key exists with value None. | Check if user is not None: or coalesce (data.get(“user”) or {}).get(“city”) |
| cur.fetchone()[0] (SQLite / PostgreSQL / MySQL) | fetchone() returns None when the SQL query matches 0 rows. | Assign row = cur.fetchone() and check if row is not None: first. |
| re.search(pat, text)[1] | re.search() and re.match() return None when no match is found. | Use walrus guard: if m := re.search(pat, text): print(m[1]) |
| soup.find(“a”)[“href”] (BeautifulSoup) | soup.find() returns None when the HTML tag is missing. | Guard tag first: tag.get(“href”) if (tag := soup.find(“a”)) else None |
| df = df.dropna(inplace=True) followed by df[“col”] | Pandas methods with inplace=True return None, overwriting df. | Remove inplace=True: df = df.dropna() |
| os.environ.get(“KEY”)[0] (or os.getenv(“API_KEY”)[:8]) | Environment variable is unset, so .get() / getenv() returned None. | Provide a fallback string: os.getenv(“API_KEY”, “”)[:8] |
Can You Fix This TypeError?
scores = [88, 95, 72] lowest = scores.sort()[0] print(lowest)
Choose the best fix:
Table of contents
- Reading the ‘NoneType’ object is not subscriptable Traceback
- ⚡ The Quick Fix: Stop Chaining In-Place Methods and Guard Against None
- How Python Determines Subscriptability & Debugging Workflow
- Common Causes of TypeError: ‘NoneType’ object is not subscriptable
- 1. Indexing In-Place List/Dict Methods ( .sort() , .reverse() , .append() ) & The reversed() Trap
- 2. The dict.get() Trap: Missing Keys vs. Explicit None ( null in JSON)
- 3. Functions Missing a return Statement on One Branch
- 4. Indexing cursor.fetchone()[0] When a Database Query Matches 0 Rows
- 5. Subscripting re.search() or re.match() ( m[0] / m[1] ) When No Match Is Found
- 6. Assigning Pandas inplace=True Operations ( df = df.dropna(inplace=True) )
- 7. The os.environ.get() / os.getenv() Slicing Trap & Web Scraping ( soup.find() )
- None vs. Empty Collections ( [] , {} , “” ): Why They Fail Differently
- The Three ‘NoneType’ Errors Compared ( not subscriptable vs. has no attribute vs. not iterable )
- Sibling object is not subscriptable Variants
- Type Annotations, Optional ( T | None ), and Static Type Narrowing
- Worked Examples: API JSON Responses & BeautifulSoup Web Scraping
- Frequently Asked Questions
- Official Documentation & Related Fixes
How Python Determines Subscriptability & Debugging Workflow
How Python Determines If an Object Is Subscriptable
Whenever you write obj[key], obj[0], or a slice like obj[1:5], CPython executes the BINARY_SUBSCR bytecode instruction (PyObject_GetItem at the C level), which looks up the __getitem__ method on type(obj):
- Containers (
list,dict,tuple,str,bytes,re.Match,DataFrame): Define__getitem__()on their class, soobj[...]succeeds. None(NoneType),int,float,bool,set, iterators (reversed()), and functions: Do not define__getitem__()on their class. EvaluatingNone[0]orNone["key"]immediately raisesTypeError: 'NoneType' object is not subscriptable.- Why
hasattr(obj, "__getitem__")Is Not a Reliable Test: Many developers check subscriptability withhasattr(obj, "__getitem__"). However,hasattr()inspects both instance attributes and class attributes—meaning it returnsTrueon an unsubscriptableSimpleNamespace(__getitem__=...)instance and returnsTrueon a raw class object likeCustomClass(which only defines__getitem__for its instances, not__class_getitem__for the class itself). Checkinghasattr(type(obj), "__getitem__")(or testing inside atry / except TypeErrorblock) reflects how CPython actually resolvesobj[...]:
def is_subscriptable(obj):
# CPython looks up __getitem__ on type(obj), not on the instance dict
return hasattr(type(obj), "__getitem__")
response = {"data": {"user": {"profile": None}}}
# Inspect each step of a chained lookup to find where None appears:
step1 = response.get("data")
step2 = step1.get("user") if isinstance(step1, dict) else None
step3 = step2.get("profile") if isinstance(step2, dict) else None
for name, val in [("response['data']", step1), ("...['user']", step2), ("...['profile']", step3)]:
print(f"{name:<18} -> type={type(val).__name__:<8} | subscriptable={is_subscriptable(val)} | repr={val!r}")Verified Output (Python 3.10.16):
response['data'] -> type=dict | subscriptable=True | repr={'user': {'profile': None}}
...['user'] -> type=dict | subscriptable=True | repr={'profile': None}
...['profile'] -> type=NoneType | subscriptable=False | repr=NonePython None vs. JSON null and SQL NULL
Developers coming from JavaScript, SQL, or Java often wonder why a JSON response containing "profile": null or a database column containing NULL triggers a NoneType error in Python:
- Python has no
nullkeyword: In Python, the absence of a value is represented exclusively by the singleton objectNone(whose class isNoneType). Writingif x == null:in Python raisesNameError: name 'null' is not defined. - Automatic Translation at Boundaries: Whenever you parse JSON with
json.loads()orresponse.json(), Python’s JSON decoder automatically converts every JSONnullinto PythonNone. Likewise, database drivers (sqlite3,psycopg2,pymysql) convert SQLNULLvalues and emptyfetchone()queries into PythonNone. - Identity Check (
is None): Because there is only oneNoneinstance in memory during a Python process, always check for it usingif x is None:orif x is not None:rather than== None.
Step-by-Step Debugging Workflow
When TypeError: 'NoneType' object is not subscriptable crashes a multi-part line, follow this 7-step workflow to isolate the exact source of None:
- Identify the exact failing line from the traceback: Look at the bottom frame of the traceback (and in Python 3.11+, check which
[...]bracket pair has^^^carets underneath it). - Break chained subscripts into separate lines: If the crashing line chains multiple lookups (
data["user"]["orders"][0]["total"]), split each step onto its own line (user = data["user"],orders = user["orders"], etc.) so the traceback points to the exact step that isNone. - Print
type(var).__name__andrepr(var)right before[...]: Confirm which expression evaluated toNone. - Check for in-place mutation methods: Verify that the variable was not assigned from
.sort(),.reverse(),.append(),.extend(),.update(), or a Pandas method withinplace=True. - Audit every
returnpath if the value came from a function: Check the function that produced the variable for missingreturnstatements, barereturnstatements, orif/elifbranches without anelse. - Check external query/lookup misses: If the variable came from
json.loads(),cursor.fetchone(),re.search(),soup.find(), oros.getenv(), inspect the raw input to see why the lookup matched nothing or containednull. - Fix the producer or add an explicit boundary guard: Never wrap
x[0]in a baretry ... except TypeError: pass. Either fix the upstream function so it returns an empty collection ([]/{}) or guard the variable withif x is not None:before subscripting.
Common Causes of TypeError: 'NoneType' object is not subscriptable
Here are the seven most frequent ways a variable becomes None right before you index it.
1. Indexing In-Place List/Dict Methods (.sort(), .reverse(), .append()) & The reversed() Trap
By design in Python, methods that mutate a mutable object in place—such as list.sort(), list.reverse(), list.append(), list.extend(), list.clear(), and dict.update()—always return None to remind you that no new object was created. Assigning their result back to a variable (items = items.sort()) or indexing them directly (items.sort()[0]) guarantees a NoneType crash.
- The Trigger (Verified 3.10.16):
scores = [88, 95, 72] # Fails: scores.sort() returns None! top_score = scores.sort()[-1] # TypeError: 'NoneType' object is not subscriptable
- The Fix (And Why
reversed(scores)[0]Also Fails):
- To sort and index on one line without mutating the original list, use built-in
sorted(scores)[0](which returns a newlist). - ⚠️ Watch out for
reversed(): Unlikesorted(), built-inreversed(scores)does NOT return a list—it returns a lazylist_reverseiteratorobject. Writingreversed(scores)[0]crashes withTypeError: 'list_reverseiterator' object is not subscriptable! To index a reversed sequence without mutating it in place, use a reversal slicescores[::-1][0](orlist(reversed(scores))[0]), or simply index from the right withscores[-1]:
scores = [88, 95, 72] # Sort and index cleanly: lowest = sorted(scores)[0] # Reverse and index cleanly (without reversed()[0] iterator crash): last_item = scores[::-1][0] # Or simply: scores[-1] print(lowest, last_item) # Prints: 72 72
2. The dict.get() Trap: Missing Keys vs. Explicit None (null in JSON)
Many developers write payload.get("user", {})["city"] or payload.get("items", [])[0] assuming that the fallback default ({} or []) protects them from NoneType errors. That assumption fails because Python distinguishes between a missing key and a key whose value is explicitly None:
- Case A — Missing Key (
{}): The key"user"is not inpayloadat all. Callingpayload.get("user", {})returns the fallback default{}. - Case B — Explicit
None({"user": None}): When a JSON API sends{"user": null, "items": null},json.loads()creates keys mapped toNone. Because the keys exist in the dictionary,payload.get("user", {})ignores the{}default and returnsNone! The same trap hits list defaults:payload.get("items", [])[0]returnsNoneand crashes onNone[0].
missing_key = {}
explicit_none = {"user": None}
print(missing_key.get("user", {})) # Prints: {} (key is absent -> returns default)
print(explicit_none.get("user", {})) # Prints: None (key exists -> returns None!)The Trigger (Verified 3.10.16):
payload = {"user": None, "items": None}
# Both lines below fail with TypeError: 'NoneType' object is not subscriptable!
city = payload.get("user", {})["city"]
first_item = payload.get("items", [])[0]- The Fix (Explicit
is not NoneGuard vs.or {}/or []Coalescing): You have two ways to guard against explicitNonevalues from.get():
- Explicit
is not NoneGuard (Most Precise): Checks specifically forNonewithout overwriting other falsy values (0,False,"") and without allocating an extra{}or[]. For lists, pairitems is not Nonewithlen(items) > 0before indexing[0]. - Boolean
or {}/or []Coalescing (Shorthand): Writing(payload.get("user") or {})replaces any falsy value (None,{},[],0,"",False) with{}. This is safe and concise when the field is strictly a nullable container, though it should never be used on numeric/boolean fields where0orFalseis valid.
payload = {"user": None, "items": None}
# 1. Explicit None Guards (for dicts and lists):
user = payload.get("user")
city = user.get("city", "Unknown") if user is not None else "Unknown"
items = payload.get("items")
first_item = items[0] if items is not None and len(items) > 0 else None
# 2. Shorthand 'or' Coalescing:
city_short = (payload.get("user") or {}).get("city", "Unknown")
items_list = payload.get("items") or []
first_short = items_list[0] if items_list else None
print(city, "|", first_item) # Prints: Unknown | NoneCan You Fix This TypeError?
payload = {"user": None} city = payload.get("user", {})["city"] print(city)
Choose the best fix when "user" is None:
3. Functions Missing a return Statement on One Branch
In Python, any function that reaches the end of its body without hitting an explicit return value statement—or that executes a bare return—automatically returns None. If an if branch returns a dictionary or list, but the else path falls off the bottom of the function, callers indexing the result crash whenever the if condition is False.
- The Trigger (Verified 3.10.16):
def fetch_config(env):
config = {"dev": {"debug": True}}
if env in config:
return config[env]
# Bug: implicitly returns None when env is not in config!
settings = fetch_config("prod")
print(settings["debug"])
# TypeError: 'NoneType' object is not subscriptable- The Fix: Ensure every execution path returns a valid dictionary (for optional configs) or raises an explicit
KeyError/ValueError(for required configs):
def fetch_config(env):
config = {"dev": {"debug": True}}
if env not in config:
raise ValueError(f"Unknown environment: {env!r}")
return config[env]4. Indexing cursor.fetchone()[0] When a Database Query Matches 0 Rows
In Python database drivers (sqlite3, psycopg2, pymysql, pyodbc) and SQLAlchemy (result.fetchone() / session.scalar()), fetchone() returns a row tuple when a record is found, but returns None when the query matches zero rows. Chaining [0] or ["id"] directly onto cursor.fetchone()[0] crashes the moment a user ID or email isn’t in the table.
- The Trigger (Verified 3.10.16):
import sqlite3
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("CREATE TABLE users (id INT, name TEXT)")
# Query matches 0 rows, so fetchone() returns None:
name = cur.execute("SELECT name FROM users WHERE id = 999").fetchone()[0]
# TypeError: 'NoneType' object is not subscriptable- The Fix: Assign
row = cur.fetchone()to a variable first, and checkif row is not None:before indexingrow[0]:
row = cur.execute("SELECT name FROM users WHERE id = 999").fetchone()
name = row[0] if row is not None else None
print(name) # Prints: None5. Subscripting re.search() or re.match() (m[0] / m[1]) When No Match Is Found
Since Python 3.6, re.Match objects implement __getitem__() so m[0] is shorthand for m.group(0) and m[1] is m.group(1). However, when a regex pattern does not match the input string, re.search() and re.match() return None. Chaining re.search(...)[1] directly without checking for a match raises TypeError: 'NoneType' object is not subscriptable.
- The Trigger (Verified 3.10.16):
import re # No '#' in string -> re.search() returns None order_num = re.search(r"Order #(\d+)", "Invoice 1042")[1] # TypeError: 'NoneType' object is not subscriptable
- The Fix: Use Python 3.8+’s assignment expression (walrus operator
:=) to verify the match succeeded before subscriptingm[1]:
import re text = "Invoice 1042" order_num = m[1] if (m := re.search(r"Order #(\d+)", text)) else None print(order_num) # Prints: None
6. Assigning Pandas inplace=True Operations (df = df.dropna(inplace=True))
In Pandas 2.0.0, methods like .dropna(), .fillna(), .sort_values(), .reset_index(), and .rename() accept an inplace=True parameter. When inplace=True is set, Pandas modifies the DataFrame in place and returns None. If you write df = df.dropna(inplace=True), you overwrite your entire DataFrame variable df with None—and the very next df["price"] or df.iloc[0] line crashes!
- The Trigger (Verified Pandas 2.0.0):
import pandas as pd
df = pd.DataFrame({"price": [10.0, None, 30.0]})
# Bug: inplace=True returns None and overwrites clean_df!
clean_df = df.dropna(inplace=True)
print(clean_df["price"])
# TypeError: 'NoneType' object is not subscriptable- The Fix: Avoid
inplace=True(which the Pandas core team is deprecating across many methods) and assign the returned DataFrame directly:
import pandas as pd
df = pd.DataFrame({"price": [10.0, None, 30.0]})
clean_df = df.dropna()
print(clean_df["price"].tolist()) # [10.0, 30.0]7. The os.environ.get() / os.getenv() Slicing Trap & Web Scraping (soup.find())
Two external lookup calls frequently return None when a resource is missing:
- The
os.environ.get("KEY")[0]/os.getenv("API_KEY")[:8]Trap: Developers often slice an environment variable to log its prefix (os.getenv("API_KEY")[:8]) or check its first character (os.environ.get("ENV")[0]). When the environment variable is unset in Docker, CI/CD, or.env,os.getenv()returnsNoneand the slice crashes withTypeError: 'NoneType' object is not subscriptable. - BeautifulSoup
soup.find("a")["href"](not run by me; noted from documentation): Callingsoup.find()returns a subscriptablebs4.element.Tagwhen found, but returnsNonewhen the HTML element is absent from the page.
- The Trigger (Verified 3.10.16):
import os
# Fails when API_KEY is not set in the environment:
key_prefix = os.getenv("API_KEY")[:8]
# TypeError: 'NoneType' object is not subscriptable- The Fix: Pass an empty string
""as the fallback default toos.getenv("API_KEY", "")[:8](oros.environ.get("KEY", "")[:1]). (💡 Tip: Use a slice[:1]rather than a single index[0]on an empty string default so""[:1]safely evaluates to""instead of raisingIndexError: string index out of range!)
import os
# Safe: returns "" if API_KEY is unset, or the first 8 chars if set
key_prefix = os.getenv("API_KEY", "")[:8]
first_char = os.environ.get("ENV", "")[:1]
print(repr(key_prefix), repr(first_char)) # '' ''None vs. Empty Collections ([], {}, ""): Why They Fail Differently
A major source of bugs in Python is treating None (the absence of any container) as if it were an empty container ([], {}, or ""). Although None, [], {}, and "" are all falsy in an if not x: check (bool(x) is False), they behave completely differently when subscripted or sliced:
| Operation on x | When x = None | When x = [] (Empty List) | When x = {} (Empty Dict) | When x = “” (Empty String) |
Index x[0] | TypeError: 'NoneType' object is not subscriptable | IndexError: list index out of range | KeyError: 0 | IndexError: string index out of range |
Key Lookup x["k"] | TypeError: 'NoneType' object is not subscriptable | TypeError: list indices must be integers or slices, not str | KeyError: 'k' | TypeError: string indices must be integers |
Slice x[:3] | TypeError: 'NoneType' object is not subscriptable | Succeeds: returns [] | TypeError: unhashable type: 'slice' | Succeeds: returns "" |
len(x) | TypeError: object of type 'NoneType' has no len() | Succeeds: returns 0 | Succeeds: returns 0 | Succeeds: returns 0 |
bool(x) | False | False | False | False |
💡 Key Takeaway on Slicing (x[:3]): Slicing an empty list [][:3] or empty string ""[:3] never raises an IndexError—it safely returns [] or "". However, slicing None[:3] crashes immediately with TypeError: 'NoneType' object is not subscriptable because None is not a sequence!
The Three 'NoneType' Errors Compared (not subscriptable vs. has no attribute vs. not iterable)
All three of Python’s famous NoneType errors share the exact same root cause (a variable evaluated to None), but the syntax you used on that variable determines which exception Python raises:
| Syntax Used on x (when x = None) | Exact Exception Raised (Verified 3.10.16) | Why Python Raised This Specific Error |
x[0], x["key"], or x[:5] (Square brackets) | TypeError: 'NoneType' object is not subscriptable | Square brackets invoke __getitem__(), which NoneType does not implement. |
x.strip(), x.get("k"), or x.append(1) (Dot attribute) | AttributeError: 'NoneType' object has no attribute '...' | Dot access looks up a method or property on NoneType, which has no public attributes. |
for i in x: or a, b = x (Iteration / Unpacking) | TypeError: 'NoneType' object is not iterable (or cannot unpack non-iterable NoneType object) | Looping and unpacking invoke iter(x) (__iter__()), which NoneType does not implement. |
Sibling object is not subscriptable Variants
What if your traceback says 'int', 'function', 'set', 'dict_keys', or 'list_reverseiterator' object is not subscriptable instead of 'NoneType'? Here are all verified sibling variants on Python 3.10.16:
| Error Message Variant (Verified 3.10.16) | What Triggered It | The Fix |
TypeError: 'int' object is not subscriptable | Indexing a number (pin = 12345; pin[0]) or overwriting a list/dict variable name with an integer counter. | Convert to a string if indexing digits (str(pin)[0]), or rename the integer counter variable. |
TypeError: 'function' object is not subscriptable | Forgetting parentheses () when calling a function before indexing its result (get_users[0] instead of get_users()[0]). | Add parentheses to call the function first: get_users()[0]. |
TypeError: 'builtin_function_or_method' object is not subscriptable | Using square brackets instead of parentheses on a built-in method (my_dict.get["key"] or my_list.append[5]). | Replace square brackets with parentheses: my_dict.get("key") or my_list.append(5). |
TypeError: 'set' object is not subscriptable | Indexing an unordered set (s = {10, 20}; s[0]). Sets do not have element positions. | Convert to a list or tuple (list(s)[0]), or use next(iter(s)) to grab an arbitrary element. |
TypeError: 'dict_keys' / 'dict_values' / 'dict_items' object is not subscriptable | Indexing d.keys()[0], d.values()[0], or d.items()[0]. In Python 3, these methods return dynamic view objects (KeysView, ValuesView, ItemsView) that support iteration and len(), but not indexing. | For keys: list(d.keys())[0] or next(iter(d.keys())). For values: list(d.values())[0] or next(iter(d.values())). |
TypeError: 'list_reverseiterator' / 'generator' object is not subscriptable | Indexing reversed(scores)[0] or a generator expression (x*2 for x in range(5))[0]. Iterators yield items lazily and cannot be indexed. | Use a reversal slice scores[::-1][0], a list comprehension [x*2 for x in range(5)][0], or next(). |
Type Annotations, Optional (T | None), and Static Type Narrowing
The most effective way to eliminate TypeError: 'NoneType' object is not subscriptable across a codebase is to make nullable types explicit using Python’s type annotations (dict[str, str] | None in Python 3.10+, or Optional[dict[str, str]] from typing) (type checker CLI outputs noted from documentation):
1. How Type Checkers Catch Unchecked Optional Subscripts
When a function can return None—whether explicitly (return None) or implicitly (falling off the end of the function)—annotating its return type as dict[str, str] | None forces Pyright / Pylance and Mypy to block any unguarded user["name"] lookup:
def find_user(user_id: int) -> dict[str, str] | None:
if user_id == 1:
return {"name": "Alice"}
return None
user = find_user(2)
print(user["name"]) # <-- Flagged in IDE before runtime!- Pyright / Pylance (VS Code):
Object of type "None" is not subscriptable (reportOptionalSubscript) - Mypy:
error: Value of type "dict[str, str] | None" is not indexable [index] - Pylint (
E1136unsubscriptable-object): Flags variables inferred asNone(such asx = scores.sort(); x[0]) when indexed with square brackets.
2. Catching Accidental Implicit return None Bugs
What if you intended find_user() to always return a dict[str, str], and forgot a return statement on one branch? Annotate the return type strictly as -> dict[str, str]: (without | None):
- Mypy immediately flags the function definition with:
error: Missing return statement [return] - Pyright / Pylance flags it with:
Function with declared return type "dict[str, str]" must return value on all code paths (reportReturnType)
3. Three Type-Narrowing Patterns That Satisfy Both Python and Your IDE
Never silence [index] or reportOptionalSubscript with # type: ignore. Instead, use one of these three type-narrowing guards so the type checker narrows dict[str, str] | None down to dict[str, str]:
# Pattern 1: if x is not None branch
user = find_user(2)
if user is not None:
print(user["name"]) # Type narrowed to dict[str, str]
# Pattern 2: Early guard clause (raise or return)
def get_user_name(user_id: int) -> str:
user = find_user(user_id)
if user is None:
raise ValueError(f"User {user_id} not found")
return user["name"] # Type narrowed to dict[str, str] for the rest of the function
# Pattern 3: isinstance() check (useful for dynamic JSON payloads)
if isinstance(user, dict):
print(user.get("name", "Guest"))Worked Examples: API JSON Responses & BeautifulSoup Web Scraping
Let’s walk through two complete production scenarios where TypeError: 'NoneType' object is not subscriptable occurs and how to make both resilient.
Worked Example 1: Multi-Level API JSON Response with null Fields
Suppose your backend consumes a user-onboarding API that returns nested JSON (payload["data"]["contacts"][0]["email"]). For active users, "contacts" is a list of dicts. However, for pending users who haven’t added a contact yet, the API sends "contacts": null.
The Crashing Code (/var/www/app/main.py):
import json
def extract_primary_email(raw_json):
payload = json.loads(raw_json)
user_data = payload.get("data", {})
contacts = user_data.get("contacts", [])
return contacts[0]["email"]
raw_response = '{"status": "pending", "data": {"id": 1042, "contacts": null}}'
print(extract_primary_email(raw_response))Verified Traceback (Python 3.10.16):
Traceback (most recent call last):
File "/var/www/app/main.py", line 10, in <module>
print(extract_primary_email(raw_response))
File "/var/www/app/main.py", line 7, in extract_primary_email
return contacts[0]["email"]
TypeError: 'NoneType' object is not subscriptableThe Thought Process & Fix:
- In
raw_response,"data"is a valid dictionary, souser_datais{'id': 1042, 'contacts': None}. - On line 6,
user_data.get("contacts", [])sees that the key"contacts"exists inuser_datawith valueNone. It ignores the[]default and assignscontacts = None. - On line 7,
contacts[0]evaluatesNone[0]and crashes withTypeError: 'NoneType' object is not subscriptable(and even if"contacts"were[],contacts[0]would crash withIndexError). - The Production Fix (Verified 3.10.16): Validate each level with
isinstance()(or provide a safe fallback for optional fields and a descriptiveValueErrorfor required fields):
import json
# Approach A (Optional field): Safely handle null/missing dicts and empty/null lists
def extract_primary_email_optional(raw_json: str, default: str | None = None) -> str | None:
payload = json.loads(raw_json)
data = payload.get("data")
if not isinstance(data, dict):
return default
contacts = data.get("contacts")
if not isinstance(contacts, list) or not contacts:
return default
first_contact = contacts[0]
if not isinstance(first_contact, dict):
return default
return first_contact.get("email", default)
# Approach B (Strict / Required field): Raise a descriptive error naming the broken path
def extract_primary_email_strict(raw_json: str) -> str:
payload = json.loads(raw_json)
data = payload.get("data")
if not isinstance(data, dict):
raise ValueError(f"Expected 'data' object in API response, got: {data!r}")
contacts = data.get("contacts")
if not isinstance(contacts, list) or not contacts:
raise ValueError(f"Expected non-empty 'data.contacts' list, got: {contacts!r}")
first = contacts[0]
if not isinstance(first, dict) or "email" not in first:
raise ValueError(f"Expected 'email' in first contact, got: {first!r}")
return str(first["email"])
raw_pending = '{"status": "pending", "data": {"id": 1042, "contacts": null}}'
raw_active = '{"status": "ok", "data": {"id": 1042, "contacts": [{"email": "dev@example.com"}]}}'
print("Optional pending:", extract_primary_email_optional(raw_pending))
print("Strict active: ", extract_primary_email_strict(raw_active))
# Verified Output:
# Optional pending: None
# Strict active: dev@example.comWorked Example 2: BeautifulSoup soup.find() Missing Tag Attribute Lookup
When scraping HTML with BeautifulSoup (bs4) (noted from documentation), bs4.element.Tag objects allow you to access HTML attributes using dictionary-style square brackets (tag["href"] or tag["data-price"]). However, if a product card is out of stock or missing a link, soup.find() returns None—and soup.find(...)["href"] immediately crashes with TypeError: 'NoneType' object is not subscriptable.
The Crashing Scraper Code:
from bs4 import BeautifulSoup
html = """
<div class="product-card">
<h2>Mechanical Keyboard</h2>
<!-- Out of stock: no <a class="buy-link"> tag rendered! -->
</div>
"""
soup = BeautifulSoup(html, "html.parser")
# Fails: soup.find("a", class_="buy-link") returns None!
buy_url = soup.find("a", class_="buy-link")["href"]
# TypeError: 'NoneType' object is not subscriptableThe Fix:
- First, check that
soup.find()actually returned aTag(notNone) before accessing attributes on it. - Second, use
tag.get("href")instead oftag["href"]on theTagobject itself—because if the<a>tag exists in the HTML without anhrefattribute (<a class="buy-link">Sold Out</a>),tag["href"]raises aKeyError, whereastag.get("href")safely returnsNone!
from bs4 import BeautifulSoup
html = """
<div class="product-card">
<h2>Mechanical Keyboard</h2>
</div>
"""
soup = BeautifulSoup(html, "html.parser")
# Safe Fix: Guard against both a missing <a> tag (NoneType) and a missing href attribute (KeyError)
link_tag = soup.find("a", class_="buy-link")
buy_url = link_tag.get("href") if link_tag is not None else None
print("Buy URL:", buy_url) # Prints: Buy URL: NoneCan You Fix This TypeError?
df = pd.DataFrame({"price": [10.0, None, 30.0]}) clean_df = df.dropna(inplace=True) print(clean_df["price"])
Choose the best fix:
Frequently Asked Questions
“Subscriptable” means an object stores items that can be accessed with square-bracket notation (obj[index], obj[key], or obj[start:stop]), which in mathematical notation is called a subscript ($a_0, a_1$). In Python, any class that defines the __getitem__() dunder method is subscriptable.
my_list.sort()[0] or my_list.reverse()[0] return None, and why did reversed(my_list)[0] also fail?In-place list methods (.sort(), .reverse(), .append(), .extend()) mutate the list in memory and intentionally return None. Meanwhile, built-in reversed(my_list) returns a lazy list_reverseiterator rather than a new list, so reversed(my_list)[0] raises TypeError: 'list_reverseiterator' object is not subscriptable. Use sorted(my_list)[0] for sorting, and my_list[::-1][0] (or my_list[-1]) for reversing.
data.get("key", {})["subkey"] or data.get("items", [])[0] still raise TypeError: 'NoneType' object is not subscriptable?dict.get("key", default) only returns default if "key" is missing from data. If "key" is present in data with a value of None (which happens whenever JSON contains "key": null), data.get() returns None. Check if val is not None: first, or coalesce with (data.get("key") or {}).get("subkey").
None in Python and null in JSON or SQL?Python does not have a null keyword—its singleton null object is named None (of type NoneType). When you parse JSON with json.loads() or fetch database rows with sqlite3/psycopg2, every JSON null and SQL NULL is automatically converted into Python’s None. Always test for it using if x is None: or if x is not None:.
[][:5] work, while slicing None[:5] raises a TypeError?An empty list [] or empty string "" is still a valid sequence that implements __getitem__(), and Python slices gracefully clamp out-of-bounds indices to return an empty sequence ([] or ""). By contrast, None is not a sequence and does not implement __getitem__(), so None[:5] fails just like None[0].
None after running df = df.dropna(inplace=True)?In Pandas, passing inplace=True to methods like .dropna(), .fillna(), .sort_values(), or .reset_index() modifies the existing DataFrame in memory and returns None. Assigning that None return value back to df = ... wipes out your DataFrame variable. Remove inplace=True (df = df.dropna()) so the method returns the modified DataFrame.
my_dict.keys()[0] or my_dict.values()[0] raise a not subscriptable error in Python 3?In Python 3, .keys(), .values(), and .items() return lightweight dynamic view objects (dict_keys, dict_values, dict_items) instead of allocating new lists. To get the first key, use next(iter(my_dict.keys())) or list(my_dict.keys())[0]. To get the first value, use next(iter(my_dict.values())) or list(my_dict.values())[0].
my_dict.get["key"] raise TypeError: 'builtin_function_or_method' object is not subscriptable?You accidentally used square brackets [] instead of parentheses () when calling .get(). Because my_dict.get is a method object, Python tries to subscript the method itself. Change the brackets to parentheses: my_dict.get("key").
Official Documentation & Related Fixes
- Master Guide: The Ultimate Python Debugging Guide: Tracebacks, Exceptions, and Fixes
- Related Error: How to Fix AttributeError: ‘NoneType’ object has no attribute ‘x’
- Related Error: How to Fix TypeError: ‘int’ object is not iterable
- Related Error: How to Fix KeyError in Python (Dictionaries, JSON & Pandas)
- Related Error: How to Fix IndexError: list index out of range
- Official Python Docs: Data Model — object.getitem()





