TypeError: builtin_function_or_method object is not iterable

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: builtin_function_or_method object is not iterable #

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().

typeerror builtin function or method object is not iterable

Here is an example of how the error occurs.

main.py
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)
We forgot to call the built-in function with parentheses, e.g. 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.

main.py
my_dict = {'name': 'Alice', 'age': 30} for key in my_dict.keys(): print(key) # 👉️ name, age

We used parentheses 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.

main.py
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.

main.py
my_str = 'a,b,c' for el in my_str.split(','): print(el) # 👉️ a, b, c

Adding parentheses to call the method resolves the issue.

Make sure you don't have any clashes with names of variables you define and built-in functions or methods.

You shouldn't use names of built-in functions and methods when defining variables.

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 function to the iter() function, the except block is run.

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.

Conclusion #

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().

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.