Explanation of error: ‘NoneType’ object is not iterable
In python2, NoneType is the type of None. In Python3 NoneType is the class of None, for example:
>>> print(type(None)) #Python2
<type 'NoneType'> #In Python2 the type of None is the 'NoneType' type.
>>> print(type(None)) #Python3
<class 'NoneType'> #In Python3, the type of None is the 'NoneType' class.
Iterating over a variable that has value None fails:
for a in None:
print("k") #TypeError: 'NoneType' object is not iterable
Python methods return NoneType if they don’t return a value:
def foo():
print("k")
a, b = foo() #TypeError: 'NoneType' object is not iterable
You need to check your looping constructs for NoneType like this:
a = None
print(a is None) #prints True
print(a is not None) #prints False
print(a == None) #prints True
print(a != None) #prints False
print(isinstance(a, object)) #prints True
print(isinstance(a, str)) #prints False
Guido says only use is
to check for None
because is
is more robust to identity checking. Don’t use equality operations because those can spit bubble-up implementationitis of their own. Python’s Coding Style Guidelines – PEP-008
NoneTypes are Sneaky, and can sneak in from lambdas:
import sys
b = lambda x : sys.stdout.write("k")
for a in b(10):
pass #TypeError: 'NoneType' object is not iterable
NoneType is not a valid keyword:
a = NoneType #NameError: name 'NoneType' is not defined
Concatenation of None
and a string:
bar = "something"
foo = None
print foo + bar #TypeError: cannot concatenate 'str' and 'NoneType' objects
What’s going on here?
Python’s interpreter converted your code to pyc bytecode. The Python virtual machine processed the bytecode, it encountered a looping construct which said iterate over a variable containing None. The operation was performed by invoking the __iter__
method on the None.
None has no __iter__
method defined, so Python’s virtual machine tells you what it sees: that NoneType has no __iter__
method.
This is why Python’s duck-typing ideology is considered bad. The programmer does something completely reasonable with a variable and at runtime it gets contaminated by None, the python virtual machine attempts to soldier on, and pukes up a bunch of unrelated nonsense all over the carpet.
Java or C++ doesn’t have these problems because such a program wouldn’t be allowed to compile since you haven’t defined what to do when None occurs. Python gives the programmer lots of rope to hang himself by allowing you to do lots of things that should cannot be expected to work under exceptional circumstances. Python is a yes-man, saying yes-sir when it out to be stopping you from harming yourself, like Java and C++ does.
The Python TypeError: NoneType Object Is Not Iterable
is an exception that occurs when trying to iterate over a None
value. Since in Python, only objects with a value can be iterated over, iterating over a None
object raises the TypeError: NoneType Object Is Not Iterable
exception.
What Causes TypeError: NoneType Object Is Not Iterable
For an object to be iterable in Python, it must contain a value. Therefore, trying to iterate over a None
value raises the Python TypeError: NoneType Object Is Not Iterable
exception. Some of the most common sources of None
values are:
- Calling a function that does not return anything.
- Calling a function that sets the value of the data to
None
. - Setting a variable to
None
explicitly.
Python TypeError: NoneType Object Is Not Iterable Example
Here’s an example of a Python TypeError: NoneType Object Is Not Iterable
thrown when trying iterate over a None
value:
mylist = None
for x in mylist:
print(x)
In the above example, mylist
is attempted to be added to be iterated over. Since the value of mylist
is None
, iterating over it raises a TypeError: NoneType Object Is Not Iterable
:
Traceback (most recent call last):
File "test.py", line 3, in <module>
for x in mylist:
TypeError: 'NoneType' object is not iterable
How to Fix TypeError in Python: NoneType Object Is Not Iterable
The Python TypeError: NoneType Object Is Not Iterable
error can be avoided by checking if a value is None
or not before iterating over it. This can help ensure that only objects that have a value are iterated over, which avoids the error.
Using the above approach, a check can be added to the earlier example:
mylist = None
if mylist is not None:
for x in mylist:
print(x)
Here, a check is performed to ensure that mylist
is not None
before it is iterated over, which helps avoid the error.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!
This may occur when I try to let ‘usrsor.fetchone’ execute twice. Like this:
import sqlite3
db_filename = 'test.db'
with sqlite3.connect(db_filename) as conn:
cursor = conn.cursor()
cursor.execute("""
insert into test_table (id, username, password)
values ('user_id', 'myname', 'passwd')
""")
cursor.execute("""
select username, password from test_table where id = 'user_id'
""")
if cursor.fetchone() is not None:
username, password = cursor.fetchone()
print username, password
I don’t know much about the reason. But I modified it with try and except, like this:
import sqlite3
db_filename = 'test.db'
with sqlite3.connect(db_filename) as conn:
cursor = conn.cursor()
cursor.execute("""
insert into test_table (id, username, password)
values ('user_id', 'myname', 'passwd')
""")
cursor.execute("""
select username, password from test_table where id = 'user_id'
""")
try:
username, password = cursor.fetchone()
print username, password
except:
pass
I guess the cursor.fetchone() can’t execute twice, because the cursor will be None when execute it first time.
None and iterables are distinct types of objects in Python. None is the return value of a function that does not return anything, and we can use None to represent the absence of a value. An iterable is an object capable of returning elements one at a time, for example, a list. If you try to iterate over a None, you will raise the error “TypeError: ‘NoneType’ object is not iterable”.
This tutorial will go through the error in detail. We will go through an example scenario and learn how to solve the error.
Table of contents
- TypeError: ‘NoneType’ object is not iterable
- Example: Function Does Not Return a Value
- Solution
- How to Avoid the NoneType Exception
- Summary
TypeError: ‘NoneType’ object is not iterable
TypeError occurs in Python when you perform an illegal operation for a specific data type. The “‘NoneType’ object is not iterable” part of the error tells us that the TypeError is referring to the iteration operation. You cannot iterate over an object that is not iterable.
Another example of a non-iterable object is an integer.
An iterable is a Python object that you can use as a sequence. You can go to the next item in the sequence using the next()
method.
d = {"two": 2, "four":4, "six": 6, "eight": 8, "ten": 10} iterable = d.keys() print(iterable)
dict_keys(['two', 'four', 'six', 'eight', 'ten'])
The output is the dictionary keys, which we can iterate over. We can loop over the items and get the values using a for loop:
for item in iterable: print(d[item])
Here we use item
as the index for the key in the dictionary. The following result will print to the console:
2 4 6 8 10
We can also create an iterator to use the next()
method
d = {"two": 2, "four":4, "six": 6, "eight": 8, "ten": 10} iterable = d.keys() iterator = iter(iterable) print(next(iterator)) print(next(iterator))
two four
The code returns the first and second items in the dictionary.
For an object to be iterable, it must contain a value. A None value is not iterable because it represents a null value.
You will not raise this error when iterating over an empty list or an empty string. In Python, list and string are iterable data types.
Let’s look at examples of trying to iterate over a NoneType, which raises the error: “TypeError: ‘NoneType’ object is not iterable”.
Example: Function Does Not Return a Value
Let’s write a program that takes a list of sandwiches and filters out those that contain cheese in the name. The program will print the sandwiches to the console. First, we will define a function that filters out the sandwiches:
def select_sandwiches(sandwiches): selected_sandwiches = [] for sandwich in sandwiches: if "cheese" in sandwich: selected_sandwiches.append(sandwich)
The function select_sandwiches()
loops over the items in the sandwiches
list. If the item contains the word cheese, we add it to the selected_sandwiches list.
Next, we will write a function that goes through the selected_sandwiches
list and prints each value to the console.
def print_sandwiches(sandwich_names): for s in sandwich_names: print(s)
With the two functions in place, we can declare a list of sandwiches for our program to search through. We need to pass the list of sandwiches to our select_sandwiches()
function:
sandwiches = ["cheese and ham", "chicken salad", "cheese and onion", "falafel", "cheese and pickle", "cucumber"] sandwiches_with_cheese = select_sandwiches(sandwiches)
We can then print all of the sandwiches that contain the word cheese to the console using the print_sandwiches()
function.
print_sandwiches(sandwiches_with_cheese)
Let’s run the code to see what happens:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) 1 print_sandwiches(sandwiches_with_cheese) in print_sandwiches(sandwich_names) 1 def print_sandwiches(sandwich_names): 2 for s in sandwich_names: 3 print(s) 4 TypeError: 'NoneType' object is not iterable
We get an error message because the function select_sandwiches()
does not return a value to iterate over. Therefore when we call print_sandwiches()
, the function tries to iterate over a None value.
Solution
To solve the error, we need to return a value in the select_sandwiches()
function. Let’s look at the revised code:
def select_sandwiches(sandwiches): selected_sandwiches = [] for sandwich in sandwiches: if "cheese" in sandwich: selected_sandwiches.append(sandwich) # Added a return statement return selected_sandwiches def print_sandwiches(sandwich_names): for s in sandwich_names: print(s) sandwiches = ["cheese and ham", "chicken salad", "cheese and onion", "falafel", "cheese and pickle", "cucumber"] sandwiches_with_cheese = select_sandwiches(sandwiches) print_sandwiches(sandwiches_with_cheese)
The select_sandwiches()
function returns the selected_sandwiches
list. Let’s run the code to see what happens:
cheese and ham cheese and onion cheese and pickle
The program selects and prints out the sandwiches that contain the word cheese.
How to Avoid the NoneType Exception
You can avoid the NoneType exception by checking if a value is equal to None before you try to iterate over that value. Let’s modify the print_sandwiches()
function:
def select_sandwiches(sandwiches): selected_sandwiches = [] for sandwich in sandwiches: if "cheese" in sandwich: selected_sandwiches.append(sandwich) # Added a return statement return selected_sandwiches def print_sandwiches(sandwich_names): if sandwich_names is not None: for s in sandwich_names: print(s) else: print('You are trying to iterate over a NoneType') sandwiches = ["cheese and ham", "chicken salad", "cheese and onion", "falafel", "cheese and pickle", "cucumber"] sandwiches_with_cheese = select_sandwiches(sandwiches) print_sandwiches(sandwiches_with_cheese)
Let’s run the code to see what happens:
cheese and ham cheese and onion cheese and pickle
The code executes successfully. However, by putting is not None
into the print_sandwiches()
function, we will not know if a function is missing a return statement. Therefore, if you encounter this error, you should accept it and resolve the issue instead of using is not None
.
Summary
Congratulations on reading to the end of this tutorial. The error “TypeError: ‘NoneType’ object is not iterable” occurs when you try to iterate over a NoneType object. Objects like list, tuple, and string are iterables, but not None. To solve this error, ensure you assign any values you want to iterate over to an iterable object. A common mistake is not adding a return statement to a function, which will make the function return None instead of a value. To solve this, ensure the function returns an iterable value.
For further reading on TypeErrors involving NoneType objects go to the article: How to Solve Python TypeError: can only join an iterable.
Go to the online courses page on Python to learn more about Python for data science and machine learning.
Have fun and happy researching!
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 TypeError: ‘NoneType’ object is not iterable
error.
In this guide, we talk about what this error means and why you may encounter it. We walk through an example to help you solve how to solve this common Python error.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
TypeError: ‘NoneType’ object is not iterable
For an object to be iterable, it must contain a value. A None value is not iterable because it does not contain any objects. None represents a null value.
There is a difference between a None object and an empty iterable. This error is not raised if you have any empty list or a string.
This is because lists and strings have an iterable data type. When the Python interpreter encounters an empty list, it does not iterate over it because there are no values. Python cannot iterate over a None value so the interpreter returns an error.
This error is common when you declare a function and forget to return a value.
An Example Scenario
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.
Start by defining a function that filters out the students’ names:
def filter_students(class_names): new_class_names = [] for c in class_names: if c.startswith("E"): 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:
def show_students(class_names): for c in class_names: 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:
students = ["Elena", "Peter", "Chad", "Sam"] 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:
show_students(students_e_name)
Let’s run our code and see what happens:
Traceback (most recent call last): File "main.py", line 14, in <module> show_students(students_e_name) File "main.py", line 8, in show_students for c in class_names: TypeError: 'NoneType' object is not iterable
Our code returns an error message.
The Solution
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 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, we have to return a value in our filter_students function:
def filter_students(class_names): new_class_names = [] for c in class_names: if c.startswith("E"): new_class_names.append(c) # We have added a return statement here return new_class_names def show_students(class_names): for c in class_names: print(c) students = ["Elena", "Peter", "Chad", "Sam"] students_e_name = filter_students(students) show_students(students_e_name)
This code returns the value of new_class_names back to the main program.
Let’s run our code to see if it works:
Our code now successfully prints out the names of the students whose names begin with “E”.
Avoiding the NoneType Exception
Technically, you can avoid the NoneType exception by checking if a value is equal to None before you iterate over that value. Consider the following code:
def filter_students(class_names): new_class_names = [] for c in class_names: if c.startswith("E"): new_class_names.append(c) return new_class_names def show_students(class_names): if class_names is not None: for c in class_names: print(c) students = ["Elena", "Peter", "Chad", "Sam"] students_e_name = filter_students(students) show_students(students_e_name)
The “show_students()” function 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 a NoneType 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.
Conclusion
The TypeError: ‘NoneType’ object is not iterable
error is raised when you try to iterate over an object whose value is equal to None.
To solve this error, make sure that any values that you try to iterate over have been assigned an iterable object, like a string or a list. In our example, we forgot to add a “return” statement to a function. This made the function return None instead of a list.
Now you’re ready to solve this common Python error in your own code.