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 likelist,tuple,str,bytes,dict,range,np.ndarray,pd.Series) or__class_getitem__(for generic type hints likelist[int],dict[str, Any]). - Built-in types that are NOT subscriptable include
int,float,bool,NoneType,set,frozenset,function,method,generator,map, andfilteriterators.
- An object is subscriptable if its type defines
- Most frequent real-world triggers and their exact fixes:
'NoneType' object is not subscriptable: Caused by chaining or assigning in-place mutating methods that returnNone(list.sort(),list.append(),list.reverse(),dict.update(),random.shuffle(), ordf.inplace=True), or a function missing areturnstatement. Fix by using non-mutating equivalents (sorted(),reversed()) or adding an explicitreturn.'function'/'method'/'builtin_function_or_method' object is not subscriptable: Caused by writingobj.method[0]orfunc[0]instead ofobj.method()[0]orfunc()[0](very common withdict.items[0],str.split[0], orresponse.json[0]).'set' object is not subscriptable: Sets are unordered hash tables and do not supports[0]. Convert to a list/tuple (next(iter(s))to grab one item in $O(1)$ without copying, orlist(s)[0]).'generator'/'dict_keys'/'dict_values'/'map' object is not subscriptable: Lazy iterators and dictionary views do not support positional indexing. Wrap withlist(...)ornext(iter(...)).'type' object is not subscriptable: Occurs when indexing a custom class (MyClass[0]) instead of an instance (MyClass()[0]), or usinglist[int]type annotations in legacy Python < 3.9 withoutfrom __future__ import annotations.
- Supporting
obj[key]in your own custom classes:- Implement
def __getitem__(self, key):on your class to make instances subscriptable withobj[key]and sliceable withobj[a:b].
- Implement
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. |
You must log in or register to comment.
