TypeError: ‘NoneType’ object is not subscriptable

Loading

The error message:

TypeError: 'NoneType' object is not subscriptable

occurs when you try to index ([]) or slice ([:]) a None value, which is not allowed in Python.


1. Causes and Solutions

Cause 1: A Function Returns None Instead of a List or String

If a function returns None, trying to access elements using [] will cause this error.

Incorrect Code:

def get_list():
print("Returning list") # No return statement, so it returns None

result = get_list()
print(result[0]) # TypeError: 'NoneType' object is not subscriptable

Solution: Return a Proper List or String

def get_list():
return ["apple", "banana", "cherry"] # Proper return value

result = get_list()
print(result[0]) # Output: apple

Cause 2: Variable Assigned None Instead of a List or String

If you accidentally assign None instead of a list or string, you cannot use indexing.

Incorrect Code:

data = None
print(data[0]) # TypeError

Solution: Ensure the Variable is a List or String

data = "Python"
print(data[0]) # Output: P

Cause 3: Forgetting to Return a Value in a Function

If a function doesn’t explicitly return a value, it returns None by default.

Incorrect Code:

def find_element():
numbers = [10, 20, 30]
numbers.index(40) # No return value if 40 is not found

result = find_element()
print(result[0]) # TypeError

Solution: Return a Proper Value

def find_element():
numbers = [10, 20, 30]
return numbers.index(20) # Return an actual index

result = find_element()
print(result) # Output: 1

Cause 4: Calling .get() on a Dictionary Without a Default Value

Using .get() on a dictionary returns None if the key is missing.

Incorrect Code:

data = {"name": "Alice"}
print(data.get("age")[0]) # TypeError: 'NoneType' object is not subscriptable

Solution: Provide a Default Value

print(data.get("age", "Unknown")[0])  # Output: U

2. Best Practices to Avoid TypeError

Check if a function returns None before using indexing
Ensure variables hold valid iterables (list, tuple, or string)
Use if result is not None: to verify before indexing
Use .get(key, default_value) when accessing dictionary values

Leave a Reply

Your email address will not be published. Required fields are marked *