TypeError: 'bool' object is not subscriptable in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: 'bool' object is not subscriptable in Python #

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.

typeerror bool object is not subscriptable

Here are 2 examples of how the error occurs.

main.py
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.

main.py
my_list = ['a', 'b', 'c'] # 👇️ reassigned to 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 have a missing comma between a boolean value and a list, make sure to place the comma between the two values.

The error means that we are using square brackets to either access a key in a specific object or to access a specific index, however the object doesn't support this functionality.

You should only use square brackets to access subscriptable objects.

The subscriptable objects in Python are:

  • list
  • tuple
  • dictionary
  • string

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.

main.py
a_list = [2, 4, 6, 8] # 👇️ <built-in method __getitem__ of list object at 0x7f71f3252640> print(a_list.__getitem__)

Conclusion #

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.