Fix - TypeError: 'method' object is not iterable in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Fix - TypeError: 'method' object is not iterable in Python #

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.

typeerror method object is not iterable

Here is an example of how the error occurs.

main.py
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)
We forgot to call the method with parenthesis, e.g. 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.

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

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

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

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

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.