Free: 4 trials of 20 minutes, no cardStart free

Craftstack Academy
Python

Python TypeError: 'NoneType' object is not subscriptable, and how to fix it

· 9 min read

You sort a list of scores and try to print the lowest one. Python stops:

Terminal
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(scores[0])
          ~~~~~~^^^
TypeError: 'NoneType' object is not subscriptable

TypeError: 'NoneType' object is not subscriptable means you used square brackets, like scores[0] or user["age"], on a variable whose value is None. None is Python's "nothing here" value, and you can't take item 0 of nothing. The error is reported on the line with the brackets, but the real mistake is almost always earlier: somewhere, the variable got None when you expected a list or a dictionary. This article shows how to find that place, and the five most common ones.

Try it yourself

Save this as main.py and run python main.py:

main.py
scores = [72, 85, 90]
scores = scores.sort()
print(scores[0])

You'll get the error above. The fix is in cause 1 below, and it's one word.

What the error means

Read the last line from the left:

  • TypeError: the problem is the type of a value.
  • 'NoneType' object: the value is None. NoneType is the type that None belongs to, the way 5 belongs to int.
  • is not subscriptable: it can't be used with square brackets. Subscripting is the name for x[0], x["key"] or x[1:3].

So the message really says: the thing before the [ is None. The ^^^ marks show the brackets that failed, and the ~~~~~~ marks under scores show which value was None.

Now ask the question that solves it: where did this variable get its value, and why was that value None?

Cause 1: list methods like sort() and append() return None

This is the most common cause by far. Methods that change a list in place, like sort(), append(), reverse() and extend(), do their work on the list and then return None. So scores = scores.sort() sorts the list and then replaces it with None.

The fix: call the method on its own line, and keep the list:

main.py
scores = [72, 85, 90]
scores.sort()
print(scores[0])
Terminal
72

If you want a new sorted list and to keep the old one, use the built-in sorted(), which returns the result:

python
print(sorted([3, 1, 2]))
Terminal
[1, 2, 3]

The same trap with append() gives a different message, because the next thing you do is call a method instead of using brackets:

main.py
names = ["Sam", "Mia"]
names = names.append("Leo")
names.append("Ava")
Terminal
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    names.append("Ava")
    ^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'append'

Same cause, same fix: names.append("Leo") on its own line.

Cause 2: a function that doesn't return anything

A function that has no return statement, or reaches its end without one, returns None. A very common version: the function prints the result instead of returning it.

main.py
def get_scores():
    scores = [72, 85, 90]
    print(scores)

result = get_scores()
print(result[0])
Terminal
[72, 85, 90]
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    print(result[0])
          ~~~~~~^^^
TypeError: 'NoneType' object is not subscriptable

The list appears on the screen, so it's tempting to think the function "gave" it to you. It didn't: print shows a value, return hands it back. Replace print(scores) with return scores.

Cause 3: a function that returns only sometimes

The sneakier version: the function returns a value in one case and falls off the end in another:

main.py
def find_user(name):
    users = {"sam": {"age": 31}, "mia": {"age": 27}}
    if name in users:
        return users[name]

user = find_user("alex")
print(user["age"])
Terminal
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    print(user["age"])
          ~~~~^^^^^^^
TypeError: 'NoneType' object is not subscriptable

For "sam" it works. For "alex", the if is false, the function ends without a return, and you get None. That's why this error often appears only for some inputs.

Two good fixes:

  • Check before you use it:
python
user = find_user("alex")
if user is None:
    print("No such user")
else:
    print(user["age"])
  • Or make the function always return something useful, such as a default value, or use users.get(name, {}) so the caller always gets a dictionary.

Use is None to check for None, not == None. It's the standard style and always correct.

Cause 4: a search that found nothing

Many functions return None to mean "not found". The classic one is re.search from the regular expression module:

main.py
import re
match = re.search(r"\d+", "no digits here")
print(match[0])
Terminal
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(match[0])
          ~~~~~^^^
TypeError: 'NoneType' object is not subscriptable

There are no digits in the text, so there's no match, and match is None. Always check: if match: print(match[0]). Dictionary .get() behaves the same way: config.get("theme") returns None when the key is missing.

Cause 5: None stored in your data

Sometimes None is a real value in your data, for example a setting that hasn't been chosen yet:

main.py
config = {"theme": None}
print(config["theme"]["color"])
Terminal
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(config["theme"]["color"])
          ~~~~~~~~~~~~~~~^^^^^^^^^
TypeError: 'NoneType' object is not subscriptable

The markers help here: the ~~~ part, config["theme"], is the value that was None, and the ^^^ part, ["color"], is the step that failed. With chained brackets, this tells you exactly which link in the chain broke.

Other errors with None

The same mistake shows up with different words depending on what you tried to do with the None:

Terminal
TypeError: 'NoneType' object does not support item assignment
TypeError: 'NoneType' object is not iterable
TypeError: object of type 'NoneType' has no len()
AttributeError: 'NoneType' object has no attribute 'append'
  • x[0] = 5 on None: item assignment.
  • for item in x on None: not iterable.
  • len(x) on None: has no len().
  • x.append(...) or any method on None: has no attribute.

All four have the same cause and the same way to find it: trace the variable back to where it became None.

Errors that look alike

  • TypeError: 'int' object is not subscriptable: the same idea with a number, for example age[0] when age is 31. You can't take an item of a single number.
  • TypeError: 'function' object is not subscriptable: you used brackets on a function name instead of calling it: get_scores[0] instead of get_scores()[0].
  • TypeError: unsupported operand type(s): the value exists but has the wrong type for + or -. See unsupported operand: 'int' and 'str'.
  • NameError: name is not defined: the variable doesn't exist at all, which is different from existing with the value None. See NameError: name is not defined.

Wrong fixes that don't help

  • Wrapping the line in try/except TypeError. It hides the symptom. The variable is still None, and the next line that uses it fails.
  • Setting the variable to [] right before the line. The error goes away, and so does your data.
  • Changing [0] to .get(0). None has no .get either: you'd get the has no attribute version.

A debugging walkthrough

A program reads orders and fails with 'NoneType' object is not subscriptable on print(order["total"]). Here's the order to check:

  1. Find the variable before the brackets: order.
  2. Find where it got its value. Search for order = in the file.
  3. If it comes from a function, open the function. Does every path end with return? Does it print instead of return?
  4. If it comes from a method, check whether the method changes things in place (sort, append, update) and returns None.
  5. If it comes from a search or .get(), ask whether "not found" is possible, and add an if ... is None check.
  6. Print the value right after it's assigned: print(repr(order)). If it shows None, you've found the line.

Practice

Predict the output, or the error, before you run each one.

  1. x = [3, 1, 2].sort(), then print(x).
  2. d = {"a": 1}, then print(d.get("b")["c"]).
  3. names = ["Sam"], then names.reverse(), then print(names[0]).

Answers. (1) It prints None, with no error, because print can show None. (2) 'NoneType' object is not subscriptable: d.get("b") is None. (3) No error: prints Sam. reverse() returned None, but the result wasn't assigned to names, so the list is fine.

Frequently asked questions

What does "'NoneType' object is not subscriptable" mean?

You used square brackets on a variable whose value is None. Find where that variable was set, and why it got None instead of a list or dictionary.

Why does list.sort() return None?

Because it sorts the list in place, and Python's convention is that methods which change an object return None. Use sorted(my_list) if you want a new list back.

How do I check if a variable is None?

if x is None:. Use is, not ==.

Why does my function return None?

It has no return statement, or one of its paths reaches the end without one. A print inside the function shows a value but doesn't return it.

Is this the same error in Python 3.8?

Yes. The message is the same in older versions. Newer versions add the ~~~ and ^^^ marks under the line, which show which part was None.

A quick checklist

  1. Look at the variable right before the [: it's None.
  2. Find the line that assigned it.
  3. Was it x = x.sort() or x = x.append(...)? Call the method on its own line.
  4. Was it a function? Make sure every path returns a value.
  5. Was it a search or .get()? Check for None before using the result.

For a method that works on every error, read how to read an error message. The Python documentation explains the None constant and why list.sort() returns it.

1 beginner error a week

One common error, what it means and how to fix it, in a short email. Free, and you can unsubscribe in any email.

Learn by writing the code yourself.

Twenty minutes with the tutor, right in your browser. No card, nothing to install.

Start the free trial
A session: the tutor's chat on the left, the code editor with a Java program and its output on the right