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.

If countryList is of type None, then you can get this error.

Let’s see a scenario in which you can get this error.

When you run above program, you will get below output:

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.

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

In Python 3, NoneType is class of 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.

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:

That’s all about TypeError: ‘NoneType’ object is not iterable.

Was this post helpful?

Leave a Reply

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