TypeError: 'NoneType' object is not subscriptable
Youβre trying to use [] on something that is None. This means a function returned None when you expected a list, dict, or other indexable object.
Fix 1: Function Returns None
Most common cause β a function that modifies in place returns None:
# β .sort() returns None (sorts in place)
numbers = [3, 1, 2]
result = numbers.sort()
print(result[0]) # π₯ NoneType is not subscriptable
# β
sort() modifies the list in place
numbers = [3, 1, 2]
numbers.sort()
print(numbers[0]) # 1
# β
Or use sorted() which returns a new list
result = sorted([3, 1, 2])
print(result[0]) # 1
Same issue with .append(), .extend(), .reverse(), .insert() β they all return None.
Fix 2: Missing Return Statement
# β Forgot to return
def get_user(id):
user = {"name": "Alice", "id": id}
# Oops β no return statement
result = get_user(1)
print(result["name"]) # π₯ NoneType
# β
Add return
def get_user(id):
user = {"name": "Alice", "id": id}
return user
Fix 3: Dictionary .get() Returned None
# β Key doesn't exist, .get() returns None
data = {"users": [{"name": "Alice"}]}
result = data.get("posts")
print(result[0]) # π₯ NoneType
# β
Check first or provide default
result = data.get("posts", [])
if result:
print(result[0])
Fix 4: Regex Match Returned None
import re
# β No match returns None
match = re.search(r'\d+', 'no numbers here')
print(match.group()) # π₯ NoneType has no attribute 'group'
# β
Check if match exists
match = re.search(r'\d+', 'no numbers here')
if match:
print(match.group())
Quick Fix Pattern
Always check for None before subscripting:
result = some_function()
if result is not None:
print(result[0])
else:
print("Got None β something went wrong")