Last modified: Apr 09, 2025 By Alexander Williams
Fix TypeError: 'type' object is not iterable
Python developers often encounter the error TypeError: 'type' object is not iterable. This error occurs when trying to iterate over a class or type instead of an instance.
What Causes This Error?
The error happens when you attempt to use a for
loop or other iteration on a class rather than an object. Classes are blueprints, not collections.
For example, trying to iterate over int
or str
directly raises this error. These are types, not iterable objects.
# Incorrect usage causing the error
for item in str:
print(item)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not iterable
Common Scenarios
This error frequently appears in these situations:
1. Confusing a class with its instances
2. Forgetting to call a constructor
3. Incorrectly using built-in types
Another common case is mixing up modules and their contents. Similar confusion can happen with ModuleNotFoundError when imports go wrong.
How To Solve It
The solution is to ensure you're working with objects, not types. Here are specific fixes:
1. Instantiate the class first:
# Correct usage with instance
my_string = "hello"
for char in my_string:
print(char)
h
e
l
l
o
2. Check your variable types:
Use type()
to verify you're working with an instance, not a class.
print(type("hello")) # <class 'str'> (instance)
print(type(str)) # <class 'type'> (class)
Real-World Example
Consider this common mistake when working with custom classes:
class Person:
def __init__(self, name):
self.name = name
# Wrong: Trying to iterate class
for attr in Person:
print(attr)
The fix is to either iterate an instance or use vars()
:
p = Person("Alice")
# Option 1: Iterate instance attributes
print(p.name) # Works
# Option 2: Use vars()
for k, v in vars(p).items():
print(f"{k}: {v}")
Prevention Tips
1. Always double-check what you're iterating over
2. Use type hints to catch issues early
3. Write tests that verify iteration behavior
Remember that similar type-related errors can occur with functions. Always ensure you're passing the right kind of objects.
Conclusion
The TypeError: 'type' object is not iterable is a common mistake. It happens when confusing classes with instances. The solution is simple: work with objects, not types.
By understanding Python's type system better, you can avoid this and related errors like ModuleNotFoundError in your projects.