Last updated: Apr 8, 2024
Reading time·2 min
The Python "TypeError: 'bool' object is not subscriptable" occurs when we use
square brackets to try to access a bool
object at a specific index or specific
key.
To solve the error, track down where the value got assigned a boolean and correct the assignment.
Here are 2 examples of how the error occurs.
my_bool = True # ⛔️ TypeError: 'bool' object is not subscriptable print(my_bool[0]) # ⛔️ TypeError: 'bool' object is not subscriptable print(my_bool['name'])
Boolean objects are not subscriptable. In other words, we can't use square brackets to access a boolean at a specific index or to try to access a boolean's key.
You have to track down where the variable got assigned a boolean, and correct the assignment to a value that is subscriptable, e.g. a string, list or a dictionary.
Make sure you haven't reassigned a subscriptable value to a boolean somewhere in your code.
my_list = ['a', 'b', 'c'] # 👇️ Reassigned to a boolean by mistake my_list = False # ⛔️ TypeError: 'bool' object is not subscriptable print(my_list[0])
We initially set the my_list
variable to a list, but then we reassigned it to
a boolean which caused the error.
You can try to remove the square brackets accessor if the value is intended to be a boolean.
If you meant to declare a dictionary and access a key, use curly braces to wrap the key-value pairs.
my_dict = {'id': 1, 'name': 'Bobby Hadz'} print(my_dict['id']) # 👉️ 1 print(my_dict['name']) # 👉️ Bobby Hadz
If the variable is meant to store a string, wrap it in quotes.
my_str = 'bobbyhadz.com' print(my_str[0]) # 👉️ b print(my_str[1]) # 👉️ o print(my_str[0:5]) # 👉️ bobby
The error means that we are using square brackets to access a key in a specific object or to access a specific index, however, the object doesn't support this functionality.
Python indexes are zero-based, so the first character in a string has an index
of 0
, and the last character has an index of -1
or len(a_string) - 1
.
You should only use square brackets to access subscriptable objects.
The subscriptable objects in Python are:
All other objects have to be converted to a subscriptable object by using the
list(),
tuple(), dict()
or
str() classes to be able to use bracket
notation.
Subscriptable objects implement the __getitem__
method whereas
non-subscriptable objects do not.
a_list = [2, 4, 6, 8] # 👇️ <built-in method __getitem__ of list object at 0x7f71f3252640> print(a_list.__getitem__)
You can learn more about the related topics by checking out the following tutorials: