How to Fix: TypeError: ‘NoneType’ object is not subscriptable

3D illustration of a key trying to open a non-existent locker, representing the 'NoneType object is not subscriptable' error.

This error is a close cousin to AttributeError: 'NoneType', In Python, the error message NoneType object is not subscriptable usually appears if you try to access an item from a variable that is None using brackets instead of a dot.

“Subscriptable” means “able to use square brackets to get an item,” like a Dictionary or a List.

This error means: You are trying to do my_variable['key'], but my_variable is None.

The Cause

This most often happens when you use a function that might return data, but sometimes returns None (nothing).

Problem Code:

def get_user_data(user_id):
    if user_id == 1:
        return {"name": "Alice", "age": 30}
    else:
        return None  # User not found

# This user exists, it works fine
user_1 = get_user_data(1)
print(user_1['name']) # Output: Alice

# This user doesn't exist
user_2 = get_user_data(2)
print(user_2)        # Output: None
print(user_2['name'])  # CRASH! TypeError: 'NoneType' object is not subscriptable

The Fix: Check for None First

Never assume a function will succeed. Always check its return value before you try to use it.

user_2 = get_user_data(2)

if user_2 is not None:
    print(user_2['name'])
else:
    print("User was not found.")

This simple if check prevents your entire program from crashing.

Similar Posts

Leave a Reply