TypeError: ‘NoneType’ object is not iterable

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.

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.

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:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in 
      3     countryList.append("italy")
      4 
----> 5 for country in getCountryList():
      6     print(country)

TypeError: 'NoneType' object is not iterable

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.

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:

India China Russia France Italy

What is NoneType?

In Python 2, NoneType is type of None

print(type(None)) #

In Python 3, NoneType is class of None

print(type(None)) #

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.

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:

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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.