Table of Contents
In this post, we will see about TypeError: NoneType object is not iterable
.
You will get this error if you are iterating over object of type None
in for
or while
loop.
Let’s understand with help of example.
1 2 3 4 5 |
countryList =["India","China","Russia","France"] for country in countryList: print(country) |
If countryList
is of type None
, then you can get this error.
Let’s see a scenario in which you can get this error.
1 2 3 4 5 6 7 8 |
countryList =["India","China","Russia","France"] def getCountryList(): countryList.append("italy") for country in getCountryList(): print(country) |
When you run above program, you will get below output:
1 2 3 4 5 6 7 8 9 10 11 12 |
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-51-1558beedb4d8> in <module> 3 countryList.append("italy") 4 ----> 5 for country in getCountryList(): 6 print(country) TypeError: 'NoneType' object is not iterable </module></ipython-input-51-1558beedb4d8> |
If you notice, we forgot to return list countryList
from getCountryList()
and that’s the reason we are getting this error.
To resolve this issue in this particular case, we need to return list countryList
from getCountryList()
and the error will be resolved.
1 2 3 4 5 6 7 8 9 |
countryList =["India","China","Russia","France"] def getCountryList(): countryList.append("Italy") return countryList for country in getCountryList(): print(country,end=' ') |
When you run above program, you will get below output:
What is NoneType?
In Python 2, NoneType is type of None
1 2 3 4 |
print(type(None)) #<type> </type> |
In Python 3, NoneType is class of None
1 2 3 4 |
print(type(None)) #<class> </class> |
Handle TypeError: ‘NoneType’ object is not iterable
You can handle this issue in multiple ways.
Check if object is None before iterating
We can explicitly check if object is None before iterating.
1 2 3 4 5 6 7 8 9 10 11 12 |
countryList =["India","China","Russia","France"] def getCountryList(): countryList.append("Italy") return countryList if getCountryList() is None: print('List is None') else: for country in getCountryList(): print(country,end=' ') |
Use try-except
We can also use try-except
to handle TypeError: 'NoneType' object is not iterable
Let’s see with the help of example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
countryList =["India","China","Russia","France"] def getCountryList(): countryList.append("Italy") return countryList returnedCountryList=getCountryList() try: for country in returnedCountryList: print(country,end=' ') except Exception as e: print('returnedCountryList is None') |
That’s all about TypeError: ‘NoneType’ object is not iterable.