In this article, we will see why we get the “TypeError: ‘NoneType’ object is not iterable” and how to resolve it.
Type Error : ‘NoneType’ usually occurs when we try to iterate over an object that is of type
None in python is a special value in Python that indicates the absence of a value. It’s commonly used to represent a default value when a function returns nothing or to indicate that a variable hasn’t yet been assigned a value.
None doesn’t represent a value that can be iterated over, trying to do so will result in a
Following is the simple example to reproduce the above TypeError
def get_data(): return None data = get_data() for item in data: print(item)
In the above example, the get_data function returns None, which is then put into the data variable. We’ll get the TypeError: ‘NoneType’ object is not iterable error when we try to iterate over data.
To fix this error, we need to make sure that the object we’re trying to iterate over is not None. We can do this by using an if statement to check if the object is None before we try to iterate over it:
def get_data(): return None data = get_data() if data is not None: for item in data: print(item)
Alternatively, we can also use the
or operator to provide a default value in case the object is
def get_data(): return None data = get_data() or  for item in data: print(item)
In this code, the
or operator returns an empty list in case
None, so the
for loop will always have something to iterate over, even if the value in