SoftwareSideHustles
Debugging

Fix "TypeError: 'NoneType' object is not subscriptable" (and Other NoneType Errors) in Python

Why Python says 'NoneType' object is not subscriptable, has no attribute, or is not iterable — the functions that silently return None, how to find the culprit, and how to fix it properly.

By Software Side Hustles Editorial Team · Published · Updated · 4 min read

Quick answer: a value you expected to be a list, dict, string or object is actually None. 'NoneType' object is not subscriptable means you used [...] on it; has no attribute 'x' means you used .x; is not iterable means you looped over it. Find which variable is None (the traceback's last line in your code), then find where it was assigned — usually a function with no return, a method like list.sort() that returns None, or a lookup that found nothing.

The NoneType error family

ErrorYou did this to None
TypeError: 'NoneType' object is not subscriptablex[0], x["key"]
AttributeError: 'NoneType' object has no attribute 'group'x.group(), x.text
TypeError: 'NoneType' object is not iterablefor i in x, list(x)
TypeError: cannot unpack non-iterable NoneType objecta, b = x
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'x + 1

They are all the same bug: something returned None and the code carried on as if it hadn't.

Cause 1: in-place methods return None

python
scores = [70, 95, 82]
top = scores.sort(reverse=True)[0]
# TypeError: 'NoneType' object is not subscriptable

list.sort(), list.append(), list.extend(), list.reverse(), dict.update(), random.shuffle() and set.add() all modify the object in place and return None. Python does this deliberately, so you cannot mistake an in-place change for a copy. Either call the method on its own line, or use the function that returns a new object:

python
scores.sort(reverse=True)
top = scores[0]
# or
top = sorted(scores, reverse=True)[0]

The classic variant is items = items.append(x), which replaces your list with None.

Cause 2: a function with no return statement

python
def load_config(path):
with open(path) as f:
config = json.load(f)
# forgot: return config
settings = load_config("app.json")
settings["debug"] # 'NoneType' object is not subscriptable

A Python function without return — or that reaches the end of a branch without one — returns None. Look out for functions where only some branches return:

python
def find_user(users, email):
for u in users:
if u["email"] == email:
return u
# falls through: returns None when not found

That may be correct behaviour, but then every caller must handle None. Type hints make this explicit — -> dict | None — and a type checker such as mypy or Pyright will flag callers that forget.

Cause 3: lookups that find nothing

Many APIs signal "not found" by returning None instead of raising:

python
match = re.match(r"(\d+)-(\d+)", "abc")
match.group(1) # AttributeError: 'NoneType' object has no attribute 'group'
CallReturns None when
re.match, re.search, re.fullmatchthe pattern does not match
dict.get(key)the key is missing
os.environ.get("VAR")the variable is not set
BeautifulSoup soup.find(...)no element matches
SQLAlchemy query.first(), session.get(...)no row matches
cursor.fetchone()no rows remain

Check before you use the result:

python
match = re.match(r"(\d+)-(\d+)", text)
if match is None:
raise ValueError(f"Expected a range like 10-20, got {text!r}")
start, end = match.groups()

From Python 3.8 the walrus operator keeps it compact: if (m := re.match(pattern, text)):.

Cause 4: values that are None by design

Optional database columns, JSON null, optional function arguments with a None default — these flow into code that assumes a value. Decide at the boundary: replace with a default (name = row["name"] or "Anonymous"), reject the input, or carry the None deliberately with a type hint saying so.

Careful with or for defaults: count = row["count"] or 10 turns a legitimate 0 into 10. Use 10 if row["count"] is None else row["count"] when zero is valid.

How to find which value is None

  1. Read the last frame of the traceback that is in your code. It shows the exact line. See how to read a stack trace.
  2. If the line has several candidates — data["user"]["orders"][0] — split it or print each part: print(type(data), type(data.get("user"))).
  3. Use the debugger: breakpoint() on the line before, then inspect variables. In VS Code or PyCharm, enable "break on raised exceptions".
  4. Python 3.11+ highlights the failing sub-expression with ^^^^ markers under the line in the traceback, which often answers the question immediately.
  5. Trace the variable back to its assignment and ask: which call could return None here?

Preventing NoneType errors

  • Use type hints with Optional[...] / X | None and run a type checker in CI.
  • Return early with clear errors rather than passing None along.
  • Prefer exceptions for "should never happen" — d[key] raising KeyError is often more helpful than d.get(key) returning None three function calls before the crash.
  • Avoid reassigning results of in-place methods. If a linter is available, Pylint flags x = x.sort() ("assignment-from-none").

Frequently asked questions

What does "subscriptable" mean?

An object is subscriptable if it supports the [] operator — it implements __getitem__. Lists, tuples, strings and dicts are; None, integers and functions are not.

Why does my function return None when I printed the value?

Printing is not returning. print(result) shows the value on screen; the caller still receives None unless you write return result.

Is if x: a good None check?

Only if empty strings, zero and empty lists should be treated the same as None. Otherwise write if x is not None:.

Why is None instead of == None?

None is a singleton, so identity is the precise check, and == can be overridden by classes. See equality operators explained.

Where this skill pays off

The x = x.sort() bug shows up in AI-written Python more often than you would expect, and spotting it instantly is part of what makes a strong code evaluator. If you can explain bugs like this clearly, read how software engineers earn money training AI models.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy