TypeError: argument of type 'bool' is not iterable (Python)


Borislav Hadzhiev

Wed Apr 20 20222 min read


Photo by John Purakal

TypeError: argument of type 'bool' is not iterable (Python) #

The Python "TypeError: argument of type 'bool' is not iterable" occurs when we use the membership test operators (in and not in) with a boolean (True or False) value. To solve the error, correct the assignment before using the in operators.

typeerror argument of type bool is not iterable

Here is an example of how the error occurs.

my_str = True # ⛔️ TypeError: argument of type 'bool' is not iterable print('a' in my_str)

We tried to use a membership test operator with a boolean (True or False) value and got the error.

Chances are you meant to use the operator with an iterable, e.g. a string or a list.

The best way to solve the error is to track down where the variable got assigned a boolean and correct the assignment.

For example, you can reassign the variable if it stores a value of an unexpected type.

my_list = True if not isinstance(my_list, list): my_list = [] print('a' in my_list) # 👉️ False

We check if the my_list variable doesn't store a list, and if it doesn't, we set it to an empty list before using the in operator.

You can use this approach with any other object, e.g. str, dict, tuple, etc.

Alternatively, you can check if the value is not a bool before using the in or not in operators.

my_str = False if not isinstance(my_str, bool): print('a' in my_str) else: # 👇️ this runs print('value is a boolean')

We check if the value is not an instance of the bool class, and if it isn't, we use the in operator to test for membership.

However, it's safer to check if the value is of the expected type, e.g. a str, a list, or a dict.

if isinstance(my_list, list): print('a' in my_list) else: print('value is not a list')

Our if statement checks if the value is an instance of the list class, and if it is, we use the in operator.

The in operator operator tests for membership. For example, x in s evaluates to True if x is a member of s, otherwise it evaluates to False.

my_str = 'hello world' print('world' in my_str) # 👉️ True print('another' in my_str) # 👉️ False

x not in s returns the negation of x in s.

All built-in sequences and set types support the in and not in operators.

When used with a dictionary, the operators check for the existence of the specified key in the dict object.

Use the search field on my Home Page to filter through my more than 1,000 articles.