/errors/python/nonetype-object-is-not-subscriptable
TypeError: 'NoneType' object is not subscriptable
verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · Python 3.13.15updated
- tool
- Python
- exit code
- 1
- versions
- Python 3.x
- os
- any
TypeError: 'NoneType' object is not subscriptable means the code used value[...] while value was None. Subscripting (indexing with []) works on lists, dicts, strings and tuples, but None has no items. The fix is to find where the variable became None: most often it holds the result of an in-place method such as list.sort(), or of a lookup that found nothing.
Reproduce it
cat > app.py <<'EOF'
items = [3, 1, 2].sort() # sort() sorts in place and returns None
print(items[0])
EOF
python app.pyOutput · exit 1
Traceback (most recent call last):
File "/tmp/work/app.py", line 2, in <module>
print(items[0])
~~~~~^^^
TypeError: 'NoneType' object is not subscriptableCommon sources of None
cat > sources.py <<'EOF'
import re
print([3, 1, 2].sort()) # in-place methods return None
print({"a": 1}.get("b")) # missing key
print(re.match(r"\d+", "abc")) # no match
def first_even(xs):
for x in xs:
if x % 2 == 0:
return x # no return after the loop
print(first_even([1, 3]))
EOF
python sources.pyOutput
None None None None
Fixes
items = sorted([3, 1, 2]) # returns a new list
print(items[0])
config = {"a": 1}
port = config.get("port", 8080) # default instead of None
m = re.match(r"\d+", text)
if m is not None:
print(m[0])Sources
Related pages
errors · pythonPython: IndentationError: unexpected indentPython raises IndentationError: unexpected indent when a line is indented deeper than its block allows. Align the line and stop mixing tabs and spaces.compare · pythonPython is vs ==: identity vs equalityIn Python == compares values and is compares identity (the same object). Use is only for None and sentinel objects. Why 256 is 256 but 257 may not be.errors · pythonModuleNotFoundError: No module named '…'Python raises ModuleNotFoundError when the package is not installed for the interpreter that runs your code. Check sys.executable, then install with -m pip.