Python TypeError: ‘bool’ object is not subscriptable

by | Programming, Python, Tips

In Python, bool is the type for the Boolean object, which is an object that represents one of two values: True or False. You cannot retrieve items from a Boolean value using the subscript operator [] like you can with a list or a tuple. If you try to use the subscript operator on a Boolean value, you will raise the TypeError: ‘bool’ object is not subscriptable.

To solve this error, ensure that when using a function that returns True or False, you do not assign its return value to a variable with the same name as a subscriptable object used in the program.

This tutorial will go through the error in detail and how to solve it with code examples.


TypeError: ‘bool’ object is not subscriptable

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type.

The subscript operator retrieves items from subscriptable objects. The operator calls the __getitem__ method, for example a[i] is equivalent to a.__getitem__(i).

All subscriptable objects have a __getitem__ method. Boolean objects are a subclass of integers and do not contain items and do not have a __getitem__ method. We can verify that Boolean objects do not have the __getitem__ method by passing a variable with a Boolean value to the dir() function:

val = True

print(type(val))
print(dir(val))
<class 'bool'>
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

If we try to subscript a Boolean value, we will raise the TypeError: ‘bool’ object is not subscriptable.

Example #1: Assigning Return Value to Same Variable Name as a Subscriptable object

Let’s look at an example where we have a function that checks if a number is even or not. The function accepts a single number as a parameter.

def is_even_func(number):

    # Check if number is an integer

    if type(number) == int:

        if number % 2 == 0:

            is_even = True

        else:

            is_even = False
    
    return is_even

The function returns True if the number is even and False if the number is odd.

Next, we will use the function to retrieve the even numbers from a list of numbers, and we will append the even numbers to a new list using a for loop. Let’s look at the code:

numbers = [1, 2, 5, 8, 10, 13]
even_numbers=[]
for number in numbers:
    even_numbers = is_even_func(number)
    

Once we have completed the for loop, we will print the first even number in the new list using the subscript operator.

print(f'First even number is {even_numbers[0]}')

Let’s run the code to see what happens:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [5], in <cell line: 1>()
----> 1 print(f'First even number is {even_numbers[0]}')

TypeError: 'bool' object is not subscriptable

The error occurs because we assigned the return value of is_even_func() to even_numbers, which is the list’s name to which we want to append. After the first iteration, the variable even_numbers is now a Boolean. We can verify this by using the type() function.

print(type(even_numbers))
<class 'bool'>

When we try to get the first item of even_numbers, we are trying to get the first item in a Boolean, which is not subscriptable.

Solution

We can use the return value from is_even_func() to create an if-statement. If is_even_func returns True, then we append the number to the even_numbers list; otherwise, continue to the following number. Let’s look at the revised code:

numbers = [1, 2, 5, 8, 10, 13]
even_numbers=[]
for number in numbers:
    if is_even_func(number):
        even_numbers.append(number)

print(even_numbers)

print(type(even_numbers))

print(f'First even number is {even_numbers[0]}')

We also included the type check to verify we still have a list after completing the for loop. Let’s run the code to see the result.

[2, 8, 10]
<class 'list'>
First even number is 2

We successfully extracted the even numbers from the original list and appended them to a new list.

Example #2: Subscript Operator with Boolean Value

Let’s look at an example where we have a CSV file containing seven players’ scores for a game. We want to sort the scores in ascending order and get the top three. The data looks like this:

player_ID,score
A,10
B,1
C,20
D,4
E,2
F,8
G,5

We will save the data as values.csv. Next, we will import the data into a DataFrame using pandas.

import pandas as pd

df = pd.read_csv('values.csv')

Next, we will try to sort the DataFrame by the score column. The sort_values() method has an ascending parameter, which needs to be either True or False. Let’s look at our attempt to sort the DataFrame:

top_three = df.sort_values(by=['score'], ascending=False[0:2])

Let’s run the code to see the result:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [16], in <cell line: 5>()
      1 import pandas as pd
      3 df = pd.read_csv('values.csv')
----> 5 top_three = df.sort_values(by=['score'], ascending=False[0:2])

TypeError: 'bool' object is not subscriptable

The error occurs because we used the subscript operator on the Boolean value False in an attempt to get a slice of the DataFrame.

Solution

We can solve this error by removing the subscript operator from the Boolean value False and moving the slice outside the sort_values() call. Let’s look at the revised code:

import pandas as pd

df = pd.read_csv('values.csv')

top_three = df.sort_values(["score"], ascending=False)[0:3]

print(top_three)

Let’s run the code to get the result:

  player_ID  score
2         C     20
0         A     10
5         F      8

We successfully sorted the DataFrame in ascending order and retrieved the top three scores.

Summary

Congratulations on reading to the end of this tutorial! The TypeError: ‘bool’ object is not subscriptable occurs when you try to retrieve items from a Boolean value using indexing. If you call a function that returns a Boolean value, ensure that you do not assign it to an existing variable name belonging to a subscriptable object. Typically, developers use functions that return Boolean values in conditional statements.

If you want to slice a sorted DataFrame, make sure you do not try to slice any Boolean values that are parameters to the sort_values or sort_index methods.

For further reading on TypeErrors, go to the article: How to Solve Python TypeError: ‘NoneType’ object is not subscriptable

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee