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.
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!
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!
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.
Typeerror nonetype object is not iterable error occurs when we try to iterate any NoneType object in the place of iterable Python objects. Actually, String, List, and tuple are iterable objects in python. We need to make sure that before iterating these objects, It must not be empty. In this article, We will see how we can fix this error with examples.
Well, We before starting this section. Let’s replicate this error in a very easy way.
my_list=None
for ele in my_list:
print(ele)
Since my_list is of NoneType class hence when we tried to iterate the same. We get this error. Actually NoneType is the class for None.
How to check any pthon object is iterable or Not ?
Any python object is iterable if its class has __iter__() method. Lets see with an example. Since you know list is an iterable object.
print(dir(list))
The output present the internal methods for list python object.
[‘__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__delitem__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__gt__’, ‘__hash__’, ‘__iadd__’, ‘__imul__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__reversed__’, ‘__rmul__’, ‘__setattr__’, ‘__setitem__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘append’, ‘clear’, ‘copy’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse’, ‘sort’]
but NoneType does not contain the same.
typeerror nonetype object is not iterable ( Solutions )-
We can avoid or fix this issue by object type check. We can do it in three different ways.
Solution 1: Using type() function-
The best way to avoid this error is to check the type of iterable object type before each iteration.
my_list=None
if(type(my_list)!=None):
print("object is None")
else:
for ele in my_list:
print(ele)
Solution 2 : Handling nonetype object with try-except :
Well Ideally, We should avoid error while writing the code. But In some run time scenario we have to handle it. In that scenario, we can use the try-except over the code. This way we can plan the control over this unwanted situation( Nonetype object is not iterable).
my_list=None
try:
for ele in my_list:
print(ele)
except:
print("This was an exception with None type object")
Solution 3: using isinstance() –
This isinstance() function checks the type of the class and return boolean and returns the True if object type is match. We will use isinstance() function to check the type of iterable oject and if is None , we can change the control for the code.
my_list=None
if(isinstance(my_list,list)):
for ele in my_list:
print(ele)
else:
print("object is not list but NoneType")
Nonetype object is not iterable ( Scenarios) :
It is very common as we all know that the append function returns nothing. But we do the code in the same way.
my_list=[1,2,3]
list_iter=my_list.append(4)
for ele in list_iter:
print(ele)
In the above example, we can see that list _iter is None because it holds the values after my_list.append(4) statement. As we have already mentioned that append returns None object.This was just to introduce you to a real scenario. There may be many more situations like this list append in tuple and string. But the root cause will always the same. Hence we need to follow the cycle avoidance and handler as mentioned above.
Apart from append() , there are multiple function which returns NoneType object and create above error. Here are some of those list function- pop(), remove(), insert(),extend(),clear().
I hope this article will be your strong knowledge base for this error( nonetype object is not iterable). In case you have any queries, please comment below.
Similar Errors –
typeerror float object is not iterable : Step by Step Solution
Typeerror int object is not iterable : Root cause and Fix
Thanks
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
We respect your privacy and take protecting it seriously
Thank you for signup. A Confirmation Email has been sent to your Email Address.
Something went wrong.
In this post we are going to understand how to fix Fixed Typeerror: nonetype the object is not iterable Python. The Python iterable object like lists, tuples, sets, dictionaries, and strings are called iterable objects. The iterable objects mean we simply loop over or iterate over with the help of a loop. We can only iterate over these objects if that object has a value. If we iterate over a None or null object, “TypeError: ‘NoneType’ object is not an iterable error” will encounter.
What is a NoneType error in Python?
The iterable objects must contain a value to iterate over or loop over. The None object is represent null values or the absence of value in the Python object, We can’t loop through the none values so “TypeError: ‘NoneType’ object is not iterable error"
is raised. This error encounters mostly when we forget t return the value for a function.
The empty and None are not the same in python. None is returned values of function that does not have any values or absence of value and it represents a null value. whereas empty means an empty value.
Why “Python nonetype object is not iterable” error occurrs
The “Python nonetype object is not iterable” occurs when a function does not return any values or absence of value. In the below example the function dict_add() does not return any values that the mean value is null, So while iterating over the none dictionary raise TypeError: 'NoneType' object is not an iterable error.
def dict_add(): mydict = {'name':'Rack','Age':20,'Marks':100} mydict['City'] ='US' #return mydict mydict = dict_add() for key in mydict: print(key, ':', mydict[key])
Output
TypeError: 'NoneType' object is not iterable
1. How to fixed Typeerror: nonetype object is not iterable Python
- Check iterable is none
- By using the Try-except block
1.1 typeerror nonetype object is not iterable dictionary
We can fix Typeerror: nonetype object is not iterable” Python error by adding None check before iterating over the iterable. In this example, we are checking if the dictionary return by the dict_add() function is none with the help of this code if mydict is None:
- When the
mydict is none then
display the message to avoid the type error.
When the mydict is not null then
iterating over the dictionary and displaying corresponding key and value
def dict_add(): mydict = {'name':'Rack','Age':20,'Marks':100} mydict['City'] ='US' #return mydict mydict = dict_add() if mydict is None: print('The dictionary is None') else: for key in mydict: print(key, ':', mydict[key])
Output
1.2 typeerror nonetype object is not iterable using try-except block
In this example, we are using to try-catch block to handle the”TypeError: ‘NoneType’ object is not iterable error” dictionary. In the try-catch block, we have written for loop code. Let us understand with an example.
def dict_add(): mydict = {'name':'Rack','Age':20,'Marks':100} mydict['City'] ='US' #return mydict mydict = dict_add() try: for key in mydict: print(key, ':', mydict[key]) except Exception as e: print('The dictionary is None')
Output
2. typeerror: ‘nonetype’ object is not iterable list
In this example, we will learn how to fix “typeerror
:
'nonetype'
obj
ect is not iterable list
“.We have written In the try-catch block, for loop code inside the try-catch block to handle type-error. We can use both approaches to handle this error with a list.
- check iterable is none
- By using the Try-catch block
2.1 Check iterable list is none
In this example first, we will check if the list is null or none to avoid a type error.
def list_add(): mylist = [3,6,9] mylist.append(12) #return mylist mylist = list_add() if mylist is None: print('The list is None or null') else: for item in mylist: print(item)
Output
2.2 Using the try-catch block
In this example, we are using a try-catch block to handle the type error with the list.
def list_add(): mylist = [3,6,9] mylist.append(12) #return mylist mylist = list_add() try: for item in mylist: print(item) except Exception as e: print('The list is None or null')
Output
Summary
In this post we have learned how to Fixed Typeerror: nonetype
object is not iterable Python.
Have you encountered this error code while coding on Python? Have you had no luck in resolving the problem? Before scouring the internet for an array of potential solutions, try these simple solutions.
They might save you countless hours skimming through various forums for the precise solution to your problem.
This error is one of the most commonly encountered errors while working on a Python code. If you are facing this error, it is probably the cause of a for or while loop on a project.
Essentially, TyperError: ‘NoneType’ object is not iterable means that the object you are attempting to iterate a ‘For’ loop on is a ‘None’ object. ‘NoneType’ can mean various things depending on which Python you are using.
In python2, ‘NoneType’ is the type of ‘None’. In python3, ‘NoneType’ is the class of ‘None’.
Causes of TypeError: ‘NoneType’ object is not iterable
As I alluded to in the intro paragraph, there is a myriad of potential solutions to this issue as there is a myriad of potential causes based on what each individual person has coded to end up at this issue.
However, to simplify this, it is best to start at what the most likely or simple causes of this issue might be.
One of the most probable causes of this error could be that the function returning data is setting the value of the data to ‘None’.
Another common reason could be that you forgot to return any data at all. If you have no data to return, your issue might stem from the fact that you forgot to add a conditional.
Ultimately, the cause of this issue will lie somewhere in the space where you should be returning the data or adding a conditional.
While there are a number of different causes for TypeError: ‘NoneType’ object is not iterable, to fix these issues is fairly simple. You must rewrite the final line of code in the set to return the data to the function.
There could be an infinite number of different reasons for why that line of code is not properly returning the data. Therefore, we will go over a number of example problems and solutions below.
1.Check if the Object is ‘None’ or Not
A very common, and rather unobvious, issue that creates TypeError: ‘NoneType’ object is not iterable is that the function returning data is setting the value of the data to ‘None’.
If you believe that this is the case, you can check before iterating on an object if that object is ‘None’ or not. You can do this by following the template below.
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
2.Write the ‘For’ Loop in the ‘try-except’ Block
If the method above does not work, you might have to write the ‘for’ loop in a ‘try-except’ block. You can do this by following the template below.
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
3.Assign an Empty List to the Variable if it is ‘None’
If neither of the solutions listed above work for you, try assigning an empty list to the variable. You can do this by following the template below.
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
4.Check for Typos
It is also very likely that the TypeError: ‘NoneType’ object is not iterable issue has been caused by a typo. Double-check your code to make sure you have not made any typos.
Displayed below is an example of a very common type of typo that causes this error.
def remove_duplicates(input_list):
new_list = [ ]
old = 0
if input_list = = new_list:
print “Empty”
else:
for i in input_list:
if i not in new_list:
new_list:append(i)
return new_list
5.Add a Conditional
If you want to avoid running a ‘For’ at all in cases where the object has a ‘None’ value, you must remember to include a conditional. To include a conditional, follow the template below.
if input_list is None
print “No values in input_list”
else:
for input in input_list:
# do stuff with input
There are two issues here. The first issue here is that the final line of code should read “return newlist” and not “return new_list”. The second issue is that the input list is [ ], therefore the if condition should be “if not inputlist”.
Obviously, there are many other potential typos that you may run into writing your own code, however, this example might provide as an excellent reference to double-check your own work and make sure you are free from user error.
In Conclusion
The TypeError: ‘NoneType’ object is not iterable error is one of the most frequently encountered errors while working on a Python code. Therefore, it is possible that the issue could be stemming from a myriad of different problems.
As I alluded to in the intro paragraph, there are a myriad of potential solutions to this issue as there are a myriad of potential causes based on what each individual person has coded to end up at this issue.
However, the solutions I have listed above will provide an excellent reference point regardless of what your particular issue is.
To reiterate, one of the most probable causes of this error could be that the function returning data is setting the value of the data to ‘None’.
Another common reason could be that you forgot to return any data at all. If you have no data to return, your issue might stem from the fact that your forgot to add a conditional.
Ultimately, the cause of this issue will lie somewhere in the space where you should be returning the data or adding a conditional.
In Python, certain iterable objects such as a string, list, tuple, dictionary, and set can be iterated over using an iterator-like
for
loop. But if we try to iterate over a non-iterable object, we receive the TypeError with an error message. If we try to iterate over a None value, we encounter the »
TypeError: 'NoneType' object is not iterable
» Error.
In this Python guide, we will discuss Python’s «TypeError: ‘NoneType’ object is not iterable» in detail and learn how to debug it. We will also walk through some common example scenarios that demonstrate this error in a Python program. Let’s get started with the error.
Python
for
loop is an iterator that can iterate over iterable objects like a string, list, tuple, etc. But if we try to iterate over a non-iterable object like
None
, Python would throw the error «TypeError: ‘NoneType’ object is not iterable». The Error statement has two parts Exception Type and Error Message.
- TypeError (Exception Type)
- ‘NoneType’ object is not iterable (Error Message)
1. TypeError
TypeError is a standard Python exception. Python raises this exception in
a program
when we perform an unsupported operation or function on a Python object. As
None
is a non-iterable object. When we perform an iteration over it, we receive the TypeError Exception.
2. ‘NoneType’ object is not iterable
NoneType
is the base type for the
None
value. We can check it using
type(None)
statement. The Error message ‘NoneType’ object is not iterable means we are trying to iterate over the None value, which is unsupported in python.
Example
# iterate over None Value
for i in None:
print(i)
Output
Traceback (most recent call last):
File "main.py", line 2, in
for i in None:
TypeError: 'NoneType' object is not iterable
In this example, we are trying to iterate over a
None
value using
for
loop, that’s why the Python interpreter is throwing this error.
Common Example Scenario
The most common mistake that many python learners commit is when they do not have a complete idea about the return statement of a function or method. Many methods are associated with an object that returns None and performs the in-place operation on the object.
Example
The Python list’s
sort()
method perform the in-place sorting and return
None
. And when we assign the
sort()
method returns value to the list object, and try to iterate over it, we encounter the TypeError with message NoneType
object
is not iterable
.
prices = [899, 1299, 299, 450, 99]
# sort the prices list
prices = prices.sort() #retrun None
# print the pricing
for price in prices:
print(price, end =" - ")
Output
Traceback (most recent call last):
File "main.py", line 7, in
for price in prices:
TypeError: 'NoneType' object is not iterable
Break the output
In this example, we are receiving the error in line 7 with
for price in prices:
statement. By reading the error statement
TypeError: 'NoneType' object is not iterable
and the line error, we can conclude that we are trying to iterate over a None value.
This means the value of
prices
in line 7 with
for
loop statement is
None
. The value of
prices
change to None because in line 4, we are assigning the return value of
prices.sort()
method to
prices
, using statement
prices = prices.sort()
. The
sort()
method does not return any value means it return
None
, and when we tried to iterate over the None
prices
value, we encountered the Error.
Solution
Whenever we encounter this error, the first thing we need to check is the value of the iterable object that we are iterating. We need to look for the statement that is changing the value of the iterable object to None. In the above example, the assignment of the sort() method is changing the value of our list object to
None
. And to solve it all, we need to do is not assigning the return value.
prices = [899, 1299, 299, 450, 99]
# sort the prices list
prices.sort()
# print the pricing
for price in prices:
print(price, end =" - ")
Output
99 - 299 - 450 - 899 - 1299 -
Conclusion
The Error «TypeError: ‘NoneType’ object is not iterable» is raised in a Python program
when we try to iterate over a variable that value is None. Many Python learners encounter this error when they reassign a None value to an existing iterable object and only try to iterate that value. To debug this error, we need to ensure that the value we are trying to iterate must be an iterable object, not None.
If you are still getting this error in your Python program, you can share your code and query in the comment section. We will try to help you in debugging.
People are also reading:
-
Python Interview Questions
-
How to become a Python Developer?
-
Best Python Projects
-
Top Python IDEs
-
Best Python Interpreters
-
Best way to learn python
-
NumPy Matrix Multiplication
-
Best Python Books
-
Online Python Compiler
-
Replace Item in Python List