ErrorPython
TypeError: NoneType object is not subscriptable
Why TypeError: NoneType object is not subscriptable happens, the common ways a value quietly becomes None, and how to trace it to the real cause.
Last updated
ErrorPython
TypeError: 'NoneType' object is not subscriptable
What it means: Somewhere in your code you tried to index or slice a value (`x[0]`, `x['key']`) that turned out to be `None` instead of the list, dict, or string you expected.
Likely causes
Most probable first — with how to confirm.
- 1.A function you called returns `None` implicitly — no `return` statement on some code path, or a bare `return` — and you're indexing its result directly; check every `return` path of that function, especially early returns.
- 2.A dict lookup with `.get('key')` returns `None` when the key is missing, unlike `dict['key']`, which would raise `KeyError` instead — and that `None` is then indexed into.
- 3.An API call, regex match, or database query that can legitimately return 'nothing found' (`re.match` returning `None`, an ORM `.first()` returning `None`) is used without checking for that case first.
- 4.A variable was set to `None` as an initial placeholder, and a conditional that was supposed to overwrite it with a real value didn't run on this path.
Fixes
Safest first; destructive ones are called out.
- →Find the exact line from the traceback and check what's `None` there — print it or drop into a debugger (`pdb`, `breakpoint()`) right before the failing line to confirm which variable is unexpectedly `None`.
- →Add an explicit check before indexing — `if result is not None: result[0]` — and decide what should actually happen in the `None` case instead of assuming it can't occur.
- →For a dict lookup, use `.get('key', default)` with a sensible default, or confirm with `'key' in d` before indexing, rather than assuming the key exists.
- →Trace back to why the value became `None` in the first place — fixing the symptom at the indexing site often just moves the bug rather than removing it.