π§ Error Fixes
Β· 1 min read
Python TypeError: 'NoneType' Object Is Not Subscriptable β How to Fix It
TypeError: 'NoneType' object is not subscriptable
Youβre using [] on a value thatβs None. A function probably returned None instead of a list or dict.
Fix 1: Check the return value
# β .append() returns None
items = [1, 2, 3].append(4)
print(items[0]) # TypeError! items is None
# β
append modifies in place
items = [1, 2, 3]
items.append(4)
print(items[0]) # 1
Other methods that return None: .sort(), .reverse(), .extend(), .insert().
Fix 2: Function returns None
def find_user(name):
for user in users:
if user["name"] == name:
return user
# No return = returns None!
# β If user not found, result is None
result = find_user("Bob")
print(result["email"]) # TypeError!
# β
Check first
result = find_user("Bob")
if result:
print(result["email"])
Fix 3: Dictionary .get() returns None
data = {"users": [{"name": "Alice"}]}
# β .get() returns None if key missing
items = data.get("posts")
first = items[0] # TypeError!
# β
Provide default
items = data.get("posts", [])
first = items[0] if items else None
Related resources
Related: Pip Install Error Fix