πŸ”§ Error Fixes

Python TypeError: 'NoneType' Object Is Not Subscriptable β€” Fix


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")