Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "TypeError: 'method' object is not iterable" occurs when we try to
iterate over a method instead of an iterable (e.g. a list). To solve the error,
make sure to call the method, e.g. my_method()
if it returns an iterable
object.
Here is an example of how the error occurs.
class Employee(): def get_list(self): return ['Alice', 'Bob', 'Carl'] emp = Employee() # ⛔️ TypeError: 'method' object is not iterable for el in emp.get_list: # 👈️ forgot to call method print(el)
emp.get_list()
, so our code actually tries to iterate over the method and not over the list.To solve the error, make sure to call the method.
class Employee(): def get_list(self): return ['Alice', 'Bob', 'Carl'] emp = Employee() for el in emp.get_list(): print(el) # 👉️ Alice, Bob, Carl
We used parenthesis to invoke the method, so now we iterate over the list that the method returns.
Another common cause of the error is having a variable and a method with the same name.
class Employee(): get_list = ['Dean', 'Emma'] def get_list(self): return ['Alice', 'Bob', 'Carl'] emp = Employee() # ⛔️ TypeError: 'method' object is not iterable for el in emp.get_list: print(el)
The method shadows the variable with the same name, so when we try to iterate over the list, we actually end up iterating over the method.
To solve the error, rename the method or the variable.
class Employee(): my_list = ['Dean', 'Emma'] def get_list(self): return ['Alice', 'Bob', 'Carl'] emp = Employee() for el in emp.my_list: print(el) # 👉️ Dean, Emma
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 method 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.