What this error means

You tried to use square brackets [] to access an element or slice from None. Only sequences (lists, strings, tuples) and dictionaries can be subscripted (accessed with []).

Common causes

  • A function returned None instead of a list or dictionary.
  • You forgot to return a value from a function.
  • A variable was set to None when you expected a list or dict.

Example that causes the error

def get_items():
    items = [1, 2, 3]
    # Forgot to return items

result = get_items()
first = result[0]  # TypeError: result is None

How to fix it

Make sure your function returns the value:

def get_items():
    items = [1, 2, 3]
    return items  # Return the list

result = get_items()
first = result[0]  # OK: result is [1, 2, 3]

Check for None before indexing

result = some_function()
if result is not None:
    first = result[0]
else:
    print("Result is None")

Use try-except

result = some_function()
try:
    first = result[0]
except TypeError:
    print("Cannot index None")
    first = None