(Fixed) Python TypeError ‘bool’ object is not subscriptable

5/5 - (1 vote)

Problem Formulation

Consider the following minimal example where a TypeError: 'bool' object is not subscriptable occurs:

boo = True
# or:

This yields the following output:

Traceback (most recent call last):
File "C:UsersxcentDesktopcode.py", line 2, in <module>
TypeError: 'bool' object is not subscriptable

Solution Overview

Python raises the TypeError: 'bool' object is not subscriptable if you use indexing or slicing with the square bracket notation on a Boolean variable. However, the Boolean type is not indexable and you cannot slice it—it’s not iterable !

In other words, the Boolean class doesn’t define the __getitem__() method.

boo = True
boo[0] # Error!
boo[3:6] # Error!
boo[-1] # Error!
boo[:] # Error!

You can fix this error by

converting the Boolean to a string using the str() function because strings are subscriptable, removing the indexing or slicing call, defining a dummy __getitem__() method for a custom “Boolean wrapper class”.

<div class=