Python TypeError: argument of type is not iterable
The code tries to iterate over a value that is not iterable.
Explanation
TypeError occurs when you try to use the in operator or iterate over a value that doesn't support iteration. For example, checking if a value is "in" an integer or trying to loop over None. This commonly happens when a function returns None instead of a list, when a variable type is assumed but different, or when dictionary keys/values are accessed incorrectly.
Common Causes
- Function returns None instead of iterable
- Variable type assumed incorrectly
- Using in operator on non-iterable
- Database query returning None
- API response not a list
Solution
Check the variable type before iterating using isinstance() or type(). Ensure functions return iterable types (lists, tuples, generators) instead of None. Use list() to convert iterables to lists if needed. For dictionaries, iterate over .keys(), .values(), or .items(). Add type hints to functions to clarify expected types. Debug with print(type(variable)) to see what type the variable actually is.
Code Example
# Function returns None instead of a list
def get_users():
if not users:
return None # problem!
return users
# This causes TypeError: argument of type 'NoneType' is not iterable
for user in get_users():
print(user)
# Fix: return empty list instead of None
def get_users():
if not users:
return []
return users
# Check before iterating
data = get_data()
if data is not None:
for item in data:
process(item)
# For dictionaries
config = {'host': 'localhost', 'port': 3306}
for key, value in config.items():
print(key, value)
Error Information
Language
python
Difficulty
Beginner
Views
12
Related Errors
Python
Python ImportError
Python found the module but failed to load it due to a dependency or attribute issue.
Python
Python TabError
The code uses inconsistent indentation by mixing tabs and spaces.
Python
Python KeyError
The code tries to access a dictionary key that doesn't exist.
Python
Python UnicodeDecodeError
Python failed to decode bytes into a string using the specified encoding.