TypeError: 'NoneType' object is not subscriptable
Python · updated 2026-10-09
Raised on a line that uses square brackets (x[0], x['key'], x[1:]) when x is None. Python 3.11 and later underline the failing sub-expression with carets, which tells you which value was None on a chained line.
Traceback (most recent call last):
File "/srv/app/report.py", line 22, in <module>
send_summary(load_user(42))
File "/srv/app/report.py", line 15, in send_summary
to = user["email"]
~~~~^^^^^^^^^
TypeError: 'NoneType' object is not subscriptableQuick fix
Find which value on the failing line is None (the carets point at it on Python 3.11+), then trace back to the call that produced it. Handle the empty case explicitly with if value is None, and fix functions that fall off the end without a return statement.
- Use the caret markers, or split the line, to find which object is None.
- Trace that variable back to the call that assigned it.
- Make every branch of a value-returning function end in a return.
- Handle not-found explicitly: if row is None, return early or raise a clear error.
- Don't assign the result of list.sort(), list.reverse() or random.shuffle().
# Wrong: sort() sorts in place and returns None
scores = scores.sort()
top = scores[0] # TypeError
# Right
scores.sort() # or: scores = sorted(scores)
top = scores[0]
row = cur.execute("SELECT email FROM users WHERE id = ?", (user_id,)).fetchone()
if row is None:
raise LookupError(f"user {user_id} not found")
email = row[0]Paste this into Claude Code, Cursor or Codex in the project that throws it. The agent reads this guide in plain text and applies the fix that matches your stack.
Read https://runheed.com/errors/nonetype-not-subscriptable.md and fix this error in this project.Why it happens
Function returns None on some path
A function returns a dict in the happy path but simply ends (implicitly returning None) when a condition fails or an exception is caught and logged. The caller indexes the result without knowing a None can come back.
Assigning the result of an in-place method
list.sort(), list.reverse(), list.append(), dict.update() and random.shuffle() modify the object and return None. items = items.sort() replaces your list with None, and the next items[0] fails.
Lookup that found nothing
dict.get(), os.environ.get(), re.match() and re.search(), cursor.fetchone() and ORM .first() all return None for a miss. Code written against test data that always matched breaks on the first real miss.
null in JSON data
json.loads turns null into None. data['user']['name'] fails when the API sends "user": null, even though the key exists, so a key check alone does not protect you.
Decorator that drops the return value
A wrapper that calls func(*args, **kwargs) without returning its result makes every decorated function return None. Every caller that indexes the result fails at once, often right after someone adds logging or timing.
Other fixes
- Annotate return types as Optional[...] and run mypy or pyright so unchecked None access is flagged before runtime.
- For optional nested JSON, read defensively: (data.get('user') or {}).get('name').
- Write regex code as m = re.search(...) then if m: value = m[1], never re.search(...)[1].
Same error, other wording
- TypeError: 'NoneType' object has no attribute '__getitem__'
- TypeError: 'NoneType' object does not support item assignment
Let your coding agent catch the next one
Runheed records this error in production with the stack trace, the breadcrumbs before it and, when you set it, the agent session that shipped the code, and serves it to Claude Code, Cursor or any MCP client. With it connected, you can ask:
> Find the "'NoneType' object is not subscriptable" errors in production, show the line and the request or job that triggered the latest one, work out which call returned None, and handle that case explicitly.
Setup for Python and FastAPI, Django or Flask, then have your agent fix and resolve it.
Related errors
- TypeError: Cannot read properties of undefined (reading 'x')
- ModuleNotFoundError: No module named 'x'
- UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
More in Undefined, None and type errors
- panic: assignment to entry in nil mapGo
- TypeError: slugify(): Argument #1 ($title) must be of type string, null givenPHP
- System.InvalidOperationException: Sequence contains no elements.NET
- panic: runtime error: invalid memory address or nil pointer dereferenceGo
- NoMethodError: undefined method 'email' for nilRuby
- java.lang.NullPointerException: Cannot invoke "String.toLowerCase()" because the return...Java
- System.NullReferenceException: Object reference not set to an instance of an object..NET
- TypeError: Cannot destructure property 'id' of 'undefined' as it is undefined.Node.js
- TypeError: Cannot convert undefined or null to objectNode.js
- TypeError: items is not iterableNode.js
- TypeError: x is not a functionNode.js
- TypeError: Client is not a constructorNode.js
- ReferenceError: x is not definedNode.js
- ERR_INVALID_ARG_TYPE: The "path" argument must be of type string. Received undefinedNode.js
- AttributeError: 'NoneType' object has no attribute 'x'Python
- TypeError: 'NoneType' object is not iterablePython
- KeyError: 'email'Python
- TypeError: unhashable type: 'list'Python
- AttributeError: 'dict' object has no attribute 'name'Python
- IndexError: list index out of rangePython
- TypeError: unsupported operand type(s) for +: 'int' and 'str'Python
- ValueError: invalid literal for int() with base 10: ''Python
- TypeError: __init__() got an unexpected keyword argument 'proxies'Python
- UnboundLocalError: cannot access local variable 'total' where it is not associated with a...Python
- RuntimeError: dictionary changed size during iterationPython
- ValueError: too many values to unpack (expected 2)Python
- TypeError: 'str' object is not callablePython
Other error topics
- requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.example.com'...Network and HTTP
- No signatures found matching the expected signature for payload. Are you passing the raw...Network and HTTP
- Error: self-signed certificate in certificate chainNetwork and HTTP
- error: permission denied for table profilesDatabases
- redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379. Connection...Databases
- psycopg.errors.UniqueViolation: duplicate key value violates unique constraint...Databases
- ImportError: attempted relative import with no known parent packageImports and modules
- Error: Could not load the "sharp" module using the linux-x64 runtimeImports and modules
- SyntaxError: Cannot use import statement outside a moduleImports and modules
- Error: NextRouter was not mounted.React and Next.js rendering
- Element type is invalid: expected a string (for built-in components) or a class/function...React and Next.js rendering
- ReferenceError: window is not definedReact and Next.js rendering
- TypeError: Converting circular structure to JSONJSON, parsing and validation
- json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)JSON, parsing and validation
- SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSONJSON, parsing and validation
- Error: listen EADDRINUSE: address already in use :::3000Memory, async and the process
- Error: EMFILE: too many open files, open '/app/uploads/0412.jpg'Memory, async and the process
- FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memoryMemory, async and the process
- McpError: MCP error -32001: Request timed outMCP servers and clients
- Bad Request: No valid session ID providedMCP servers and clients
- Error executing tool get_orderMCP servers and clients
Free tools: Source map stack trace decoder · Uptime and SLA downtime calculator · Error budget calculator · Stack trace formatter · JSON log viewer · HTTP status code reference.
References: Python: Built-in exceptions (TypeError), Python tutorial: More on lists (methods that return None)
Spotted a mistake? Email hello@greatwork.company. About Runheed.