Solve - TypeError: 'bool' object is not iterable in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

Solve - TypeError: 'bool' object is not iterable in Python #

The Python "TypeError: 'bool' object is not iterable" occurs when we try to iterate over a boolean value (True or False) instead of an iterable (e.g. a list). To solve the error, track down where the variable got assigned a boolean and correct the assignment.

typeerror bool object is not iterable

Here is an example of how the error occurs.

main.py
my_bool = True # ⛔️ TypeError: 'bool' object is not iterable for i in my_bool: print(i)

We are trying to iterate over a boolean (True or False), but booleans are not iterable.

You have to figure out how the value got assigned a boolean and correct the assignment to an iterable such as a list, string, tuple, etc.

Make sure you aren't reassigning an iterable to a boolean somewhere by mistake.

main.py
my_list = ['a', 'b', 'c'] # 👇️ reassigned to boolean value by mistake my_list = True # ⛔️ TypeError: 'bool' object is not iterable for i in my_list: print(i)

We initially set the my_list variable to a list but later reassigned it to a boolean which caused the error.

Another common cause of the error is passing a boolean to the built-in constructors, e.g. list(), dict(), tuple() and set().

The following 4 calls to the built-in constructors cause the error.

main.py
my_bool = False # ⛔️ TypeError: 'bool' object is not iterable list(my_bool) dict(my_bool) tuple(my_bool) set(my_bool)

To solve the error, we have to correct the assignment and figure out where the boolean value is coming from.

Here are working examples of using the 4 built-ins.

main.py
l = list(['a', 'b', 'c']) print(l) # 👉️ ['a', 'b', 'c'] d = dict(name='Alice', age=30) print(d) # 👉️ {'name': 'Alice', 'age': 30} t = tuple([1, 2, 3]) print(t) # 👉️ (1, 2, 3) s = set(['a', 'b', 'a']) print(s) # 👉️ {'a', 'b'}

You have to figure out where the boolean value came from and correct the assignment.

If you need to check if an object is iterable, use a try/except statement.

main.py
my_str = 'hello' try: my_iterator = iter(my_str) for i in my_iterator: print(i) # 👉️ h, e, l, l, o except TypeError as te: print(te)

The iter() function raises a TypeError if the passed in value doesn't support the __iter__() method or the sequence protocol (the __getitem__() method).

If we pass a non-iterable object like a boolean to the iter() function, the except block is ran.

main.py
my_bool = False try: my_iterator = iter(my_bool) for i in my_iterator: print(i) except TypeError as te: print(te) # 👉️ 'bool' object is not iterable

Examples of iterables include all sequence types (list, str, tuple) and some non-sequence types like dict, file objects and other objects that define an __iter__() or a __getitem__() method.

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