TypeError: 'function' object is not iterable in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: 'function' object is not iterable in Python #

The Python "TypeError: 'function' object is not iterable" occurs when we try to iterate over a function instead of an iterable (e.g. a list). To solve the error, make sure to call the function, e.g. my_func() if it returns an iterable object.

typeerror function object is not iterable

Here is an example of how the error occurs.

main.py
def get_list(): return ['a', 'b', 'c'] # ⛔️ TypeError: 'function' object is not iterable for el in get_list: # 👈️ forgot to call function print(el)
We forgot to call the function with parentheses, e.g. get_list(), so our code tries to iterate over the function and not over the list.

To solve the error, make sure to call the function.

main.py
def get_list(): return ['a', 'b', 'c'] for el in get_list(): print(el) # 👉️ a, b, c

We used parentheses to invoke the function, so now we iterate over the list that the function returns.

Another common cause of the error is having a variable and a function with the same name.

main.py
get_list = ['f', 'g'] def get_list(): return ['a', 'b', 'c'] # ⛔️ TypeError: 'function' object is not iterable for el in get_list: print(el)

The function shadows the variable with the same name, so when we try to iterate over the list, we actually end up iterating over the function.

To solve the error, rename the function or the variable.

main.py
my_list = ['f', 'g'] def get_list(): return ['a', 'b', 'c'] for el in my_list: print(el) # 👉️ f, g

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: 'function' object is not iterable" occurs when we try to iterate over a function instead of an iterable (e.g. a list). To solve the error, make sure to call the function, e.g. my_func() if it returns an iterable object.

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.