Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Anton Maksimov
The Python "TypeError: builtin_function_or_method object is not iterable"
occurs when we try to iterate over a built-in function because we forgot to call
it. To solve the error, make sure to call the built-in function, e.g.
my_dict.keys()
.
Here is an example of how the error occurs.
my_dict = {'name': 'Alice', 'age': 30} # ⛔️ TypeError: 'builtin_function_or_method' object is not iterable for key in my_dict.keys: # 👈️ forgot to call function print(key)
my_dict.keys()
, so our code actually tries to iterate over the function and not over the iterable.To solve the error, make sure to call the built-in function.
my_dict = {'name': 'Alice', 'age': 30} for key in my_dict.keys(): print(key) # 👉️ name, age
We used parenthesis to invoke the built-in function, so now we iterate over the iterable that the function returns.
Here is another example of how the error occurs when using the str.split()
method.
my_str = 'a,b,c' # ⛔️ TypeError: 'builtin_function_or_method' object is not iterable for el in my_str.split: print(el)
We forgot to call the method which caused the error.
my_str = 'a,b,c' for el in my_str.split(','): print(el) # 👉️ a, b, c
Adding parenthesis to call the method resolves the issue.
Make sure you don't have any clashes with names of variables you define and built-in function or methods.
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 function to the iter()
function, the
except
block is ran.
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.