Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Katerina Kerdi
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.
Here is an example of how the error occurs.
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.
Make sure you aren't reassigning an iterable to a boolean somewhere by mistake.
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.
list()
, dict()
, tuple()
and set()
.The following 4 calls to the built-in constructors cause the error.
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.
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.
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.
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.