Skip to content

/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

bash
cat > app.py <<'EOF'
items = [3, 1, 2].sort()   # sort() sorts in place and returns None
print(items[0])
EOF
python app.py

Output · exit 1

Traceback (most recent call last):
  File "/tmp/work/app.py", line 2, in <module>
    print(items[0])
          ~~~~~^^^
TypeError: 'NoneType' object is not subscriptable

Common sources of None

bash
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.py

Output

None
None
None
None

Fixes

python
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