Fix "'NoneType' object is not subscriptable" in Python
TypeError: 'NoneType' object is not subscriptable
- TypeError: 'NoneType' object does not support item assignment
- TypeError: 'NoneType' object is not iterable
- TypeError: cannot unpack non-iterable NoneType object
You are using [...] on a variable that is None. Most often a function has no return, or a method like list.sort() that returns None was assigned: find where the None comes from and check if x is None before indexing.
What this error means
An object is “subscriptable” if it implements __getitem__, like lists, tuples, dicts and strings. None does not. When Python evaluates x[0] or x["key"] and x is None, it raises TypeError. The error happens on the indexing line, but the real cause is upstream: the place where the variable received None. In Python a function without an explicit return returns None, and many APIs return None to signal “nothing found” instead of raising an exception.
Common causes
- Function without
return(or withreturnin only one branch): the result isNonein the other cases. - In-place method assigned:
items = items.sort(),lst = lst.append(x),random.shuffle(lst)ordf = df.dropna(inplace=True)all returnNone. - Lookup with no result:
re.match()with no match,dict.get()on a missing key,cursor.fetchone()with no row,os.environ.get()on an unset variable. nullvalue in JSON:json.loadsconvertsnulltoNone, sodata["user"]["name"]fails whenuserisnull.
Step-by-step fix
-
Identify the variable that is None
The last line of the traceback shows the faulty expression. If it chains several lookups (
a[0]["b"]), split it or inspect the values withbreakpoint().row = get_user(42) print(type(row), repr(row)) breakpoint() # then type: p row -
Make sure the function returns a value
Every execution path must end with a
return. Add an explicit return for the “not found” case or raise a clear exception.def find_user(users, user_id): for user in users: if user["id"] == user_id: return user raise LookupError(f"user {user_id} not found") -
Do not assign in-place methods
list.sort()sorts the existing list and returnsNone. Usesorted()if you want a new list, or call the method without assigning it.# wrong: items becomes None # items = items.sort() items.sort() # or items = sorted(items) -
Check for None before indexing
For APIs that return
Nonewhen nothing is found, test the result withis Nonebefore accessing its content.import re if (m := re.match(r"(\d+)-(\d+)", text)) is None: raise ValueError(f"unexpected format: {text!r}") start, end = m[1], m[2] row = cursor.fetchone() if row is None: print("no row found") else: print(row[0]) -
Provide a default for JSON data
When a field may be missing or
null, replaceNonewith an empty structure before going deeper. Paste the response into a JSON validator to see which fields arenull.user = data.get("user") or {} name = user.get("name", "anonymous") tags = data.get("tags") or [] -
Let a type checker find the other cases
Annotate returns with
X | Noneand runmypyorpyright: they flag every lookup on a value that may beNone.python -m pip install mypy mypy --strict app/
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Annotate functions that may find nothing with
-> dict | Noneand handle theNonecase explicitly. - Prefer raising a clear exception over silently returning
Nonewhen absence is abnormal. - Remember the rule: methods that modify an object in place (
sort,append,update,shuffle) returnNone.
Frequently asked questions
What does "subscriptable" mean in Python?
A subscriptable object accepts the obj[key] syntax because it implements __getitem__. Lists, dicts, tuples and strings are; None, integers and functions are not.
Why does my function return None?
Because it ends without return, or the branch that ran has none. A print() inside the function shows the value but does not return it.
Should I write if x: or if x is not None:?
Use is not None when 0, "" or an empty list are valid values: if x: would treat them as missing.
Useful tools for this error
More Python errors
- Fix "ModuleNotFoundError: No module named" in Python
- Fix "IndentationError: unexpected indent" in Python
- Fix "error: externally-managed-environment" with pip
- Fix "UnicodeDecodeError: 'utf-8' codec can't decode byte" in Python
- Fix "KeyError" in Python (dict, pandas, os.environ)
- Fix "RecursionError: maximum recursion depth exceeded" in Python
- Fix "attempted relative import with no known parent package" in Python