This is one of the most common errors we all faced at least once while working on a Python code. If you are facing a similar error then it is probably due to a for or while loop on an object.
def myfunction(data): for item in data: print(item)
In the above example, if data is None
, we will get the specified error on the second line where we are iterating over data
object. Basically this error means that the object we are trying to iterate over is NoneType
i.e. is None
. In simpler words, we are trying to run a for
loop on a None
object.
What is NoneType?
In python2, NoneType
is the type of None
.
# python2 >>> print(type(None)) <type 'NoneType'>
In Python3 NoneType
is the class of None
# python3 >>> print(type(None)) <class 'NoneType'>
When can this error occur?
As we saw, this error is reported when we try to iterate over a None
object. All we have to find out why the object is None
.
One reason could be the function returning data is setting the value of data to None
. Another reason could be that we forgot to return anything at all.
For example,
def myfunction(): a_list = [1,2,3] a_list.append(4) return a_list returned_list = myfunction() for item in returned_list: # do something with item
The above code will work just fine.
Imagine, we forgot to return the a_list
from myfunction
. We will get the TypeError: 'NoneType' object is not iterable
in the 6th line.
def myfunction(): a_list = [1,2,3] a_list.append(4) # return a_list returned_list = myfunction() for item in returned_list: # error will be reported in this line # do something with item
How to avoid this error?
One way to avoid this error is to check before iterating on an object if that object is None
or not.
def myfunction(): a_list = [1,2,3] a_list.append(4) # return a_list returned_list = myfunction() if returned_list is None: print("returned list is None") else: for item in returned_list: # do something with item
Another way to handle this error is to write the for
loop in try-except
block.
def myfunction(): a_list = [1,2,3] a_list.append(4) return a_list returned_list = myfunction() try: for item in returned_list: # do something with item except Exception as e: # handle the exception accordingly
The third way is to explicitly assign an empty list to the variable if it is None
.
def myfunction(): a_list = [1,2,3] a_list.append(4) # return a_list returned_list = myfunction() if returned_list is None: returned_list = [] for item in returned_list: # do something with item
Host your Django Application for free on PythonAnyWhere. If you want full control of your application and server, you should consider DigitalOcean. Create an account with this link and get $100 credits.