Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Anjali Mehta
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.
Here is an example of how the error occurs.
def get_list(): return ['a', 'b', 'c'] # ⛔️ TypeError: 'function' object is not iterable for el in get_list: # 👈️ forgot to call function print(el)
get_list()
, so our code actually tries to iterate over the function and not over the list.To solve the error, make sure to call the function.
def get_list(): return ['a', 'b', 'c'] for el in get_list(): print(el) # 👉️ a, b, c
We used parenthesis 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.
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.
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.
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.