What does "object is not subscriptable" mean in Python and how do you fix it? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

What does "object is not subscriptable" mean in Python and how do you fix it?

message-square
0

TypeError: '...' object is not subscriptable means you used square-bracket indexing or slicing (obj[key]) on an object whose class does not implement the __getitem__ (or __class_getitem__) protocol—such as an int, float, bool, None, set, function, or generator—and you fix it by checking why that variable holds a scalar/non-sequence instead of a list, tuple, dict, or str (commonly caused by reassigning a method that returns None in-place, forgetting parentheses on a function call, or indexing an integer loop element directly).

Basic Example

# 1. Common Cause A: Indexing a scalar integer instead of a sequence
number = 12345
# print(number[0])          # Raises: TypeError: 'int' object is not subscriptable
print(str(number)[0])       # Fix: Convert to string first -> '1'

# 2. Common Cause B: Assigning the return value of an in-place list method (returns None!)
items = [3, 1, 2].sort()    # .sort() mutates in-place and returns None
# print(items[0])           # Raises: TypeError: 'NoneType' object is not subscriptable

items = sorted([3, 1, 2])   # Fix: Use sorted() (returns a new list) -> 1
print(items[0])

# 3. Common Cause C: Forgetting parentheses `()` when calling a function/method
def get_users() -> list[str]:
    return ["Alice", "Bob"]

# print(get_users[0])       # Raises: TypeError: 'function' object is not subscriptable
print(get_users()[0])       # Fix: Invoke the function with () first -> 'Alice'

Key Details & Edge Cases

  • What “subscriptable” actually means in Python’s data model:
    • An object is subscriptable if its type defines __getitem__(self, key) (for instances like list, tuple, str, bytes, dict, range, np.ndarray, pd.Series) or __class_getitem__ (for generic type hints like list[int], dict[str, Any]).
    • Built-in types that are NOT subscriptable include int, float, bool, NoneType, set, frozenset, function, method, generator, map, and filter iterators.
  • Most frequent real-world triggers and their exact fixes:
    1. 'NoneType' object is not subscriptable: Caused by chaining or assigning in-place mutating methods that return None (list.sort(), list.append(), list.reverse(), dict.update(), random.shuffle(), or df.inplace=True), or a function missing a return statement. Fix by using non-mutating equivalents (sorted(), reversed()) or adding an explicit return.
    2. 'function' / 'method' / 'builtin_function_or_method' object is not subscriptable: Caused by writing obj.method[0] or func[0] instead of obj.method()[0] or func()[0] (very common with dict.items[0], str.split[0], or response.json[0]).
    3. 'set' object is not subscriptable: Sets are unordered hash tables and do not support s[0]. Convert to a list/tuple (next(iter(s)) to grab one item in $O(1)$ without copying, or list(s)[0]).
    4. 'generator' / 'dict_keys' / 'dict_values' / 'map' object is not subscriptable: Lazy iterators and dictionary views do not support positional indexing. Wrap with list(...) or next(iter(...)).
    5. 'type' object is not subscriptable: Occurs when indexing a custom class (MyClass[0]) instead of an instance (MyClass()[0]), or using list[int] type annotations in legacy Python < 3.9 without from __future__ import annotations.
  • Supporting obj[key] in your own custom classes:
    • Implement def __getitem__(self, key): on your class to make instances subscriptable with obj[key] and sliceable with obj[a:b].

Comparison of Common '... object is not subscriptable' Errors & Fixes

Exact Error Message Typical Broken Code Why It Happens Exact Fix
'NoneType' object is not subscriptable x = lst.sort(); x[0] or res = fn(); res["id"] .sort() / .append() returns None, or fn() fell off the end without return. Use x = sorted(lst) or ensure fn() explicitly returns a value on all branches.
'function' / 'method' object is not subscriptable data = resp.json["items"] or line.split[0] Omitted parentheses () before the square brackets [...]. Call the callable first: resp.json()["items"] or line.split()[0].
'int' / 'float' object is not subscriptable for x in nums: print(x[0]) or 123[0] x is already a scalar element inside the loop (or an unparsed number). Use x directly (print(x)), or convert to string first (str(123)[0]).
'set' / 'dict_keys' / 'generator' object is not subscriptable my_set[0] or d.keys()[0] Unordered collections and lazy iterators do not implement __getitem__. Use next(iter(my_set)) for the first item, or list(my_set)[0] for full indexing.