The error “object is not subscriptable” occurs when you are trying to access a specific element of an object using square brackets [ ] or slice notation, but that object does not support indexing or slicing. This typically happens when you try to access an element of an object that is not a sequence or doesn’t have a defined way to access its elements in a sequential manner.
To illustrate this error, consider the following examples:
data = 10 # an int object
# Trying to access an element using square brackets
print(data[0])
# Output: TypeError: 'int' object is not subscriptable
# Trying to slice the object
print(data[0:3])
# Output: TypeError: 'int' object is not subscriptable
person = {"name": "John", "age": 30} # a dictionary object
# Trying to access an element using square brackets
print(person[0])
# Output: TypeError: 'dict' object is not subscriptable
# Trying to slice the object
print(person[1:3])
# Output: TypeError: 'dict' object is not subscriptable
grouped_data = (1, 2, 3) # a tuple object
# Trying to access an element using square brackets
print(grouped_data[0])
# Output: 1
# Trying to slice the object
print(grouped_data[1:3])
# Output: (2, 3)
In the above examples, you can see that the int object (data) and the dictionary object (person) are not subscriptable. However, the tuple object (grouped_data) can be subscripted or sliced because tuples are immutable sequences that allow indexing and slicing.