Typeerror: ‘nonetype’ object is not iterable: How to solve this error in python

With Python, you can only iterate over an object if that object has a value. This is because iterable objects only have a next item which can be accessed if their value is not equal to None. If you try to iterate over a None object, you encounter the Python nonetype object is not iterable error.

Typeerror: 'nonetype' object is not iterable problem
Source: Stackoverflow

In this guide, we talk about what this error means as well as why you may encounter it. We also walk through an example to help you solve how to solve this common error: Python nonetype object is not iterable.

Python nonetype object is not iterable example, it's nothing to worry

What is NoneType?

Firstly, in Python2, NoneType is the type of None.

# python2
>>> print(type(None))
<type 'NoneType'>    

Secondly, in Python3 NoneType is the class of None

# python3
>>> print(type(None))
<class 'NoneType'>

Reasons why occur “Python nonetype object is not iterable” problem

Most important, this error: nonetype object is not iterable Python is reported when we try to iterate over a None object. All we have to find out why the object is None. Moreover, 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

So, the above code will work just fine. 

Imagine, we forgot to return the a_list from myfunction. We will also 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 “Python nonetype object is not iterable”?

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

In addition, another way to handle this error: Python nonetype object is not iterable 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

Thirdly, it 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

An Example Scenario: Python nonetype object is not iterable

Let’s write a program that takes a list of student names and filters out those that begin with “E”. We’ll print those values to the console.

Firstly, defining a function that filters out the students’ names:

1 def filter_students(class_names):
2       new_class_names = []
3       for c in class_names:
4                if c.startswith("E"):
5                          new_class_names.append(c)

This function loops through every item in the “class_names” list using a for loop. For each item, our loop checks if the item begins with the letter “E”. If it does, that name is added to the “new_class_names” list.

Next, write a function that goes through our new list and prints out each value to the console:

1 def show_students(class_names):
2      for c in class_names:
3               print(c)

Here, we declare a list of students through which our program should search. We pass this list of students through our filter_students function:

1 students = ["Elena", "Peter", "Chad", "Sam"]
2 students_e_name = filter_students(students)

This code executes the filter_students function which finds all the students whose names start with “E”. The list of students whose names begin with “E” is called students_e_name. Next, we call our show_students function to show the new list of students:

1 show_students(students_e_name)

Then, let’s run our code and see what happens:

1 Traceback (most recent call last):
2 File "main.py", line 14, in <module>
3   show_students(students_e_name)
4  File "main.py", line 8, in show_students
5   for c in class_names:
6 TypeError: 'NoneType' object is not iterable

Our code returns an error message.

The Solution of this Python nonetype object is not iterable

When we try to iterate over the variable class_names in the show_students function, our code detects a None value and raises an error. This is because the value we have passed as “class_names” is None.

This error: Python nonetype object is not iterable is caused because our filter_students function does not return a value. When we assign the result of the filter_students function to the variable students_e_name, the value None is set.

To solve this error: Python nonetype object is not iterable, we have to return a value in our filter_students function:

1 def filter_students(class_names):
2          new_class_names = []
3          for c in class_names:
4                  if c.startswith("E"):
5                            new_class_names.append(c)
6          return new_class_names

Then, this code returns the value of new_class_names back to the main program.

Let’s run our code to see if it works:

1 Elena

Our code now successfully prints out the names of the students whose names begin with “E“.

This code executes successfully because we check if class_names is a None value before we try to iterate over it. This is not a best practice in most cases because the cause of the Python nonetype object is not iterable error can be a problem somewhere else in your code.

If we add in the “is not None” check into our full program, we don’t know we missed a return statement in another function. That’s why if you see this error, you are best to accept the exception rather than handle it using an “is not None” check.

Final thoughts

The TypeError: ‘NoneType’ object is not iterable error is raised when you try to iterate over an object whose value is equal to None.

Above all, to solve this error: Python nonetype object is not iterable, make sure that any values that you try to iterate over have been assigned an iterable object, like a string or a list. To clarify, in our example, we forgot to add a “return” statement to a function. This made the function return None instead of a list. So, now you’re ready to solve this common Python error in your own code. However, if you have any inquiry about this topic, let’s CONTACT US to know more details.

Tags

Share