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!
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.
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.
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 this post, we provide 3 fixes for the TypeError: ‘NoneType’ object is not iterable Error.
The “TypeError: ‘NoneType’ object is not iterable” is an error message in Python programming language that when an operation or a function is applied to an object of inappropriate type, Python will throw out an error and stops the program from executing. This error message has two parts which are broken down into the following:
- TypeError – the object representation of the type of error encountered or being thrown.
- ‘NoneType’ object is not iterable – the error message to help developers better understand the error.
Need help with Flask template rendering https://t.co/KUI2rmUsO1 #LearnPython
I’m attempting to create a user generated list of colors. However I get the following error:
TypeError: ‘NoneType’ object is not iterable
from flask import Flask, request, make_response, render_tem…
— Programming Gurgaon (@programmingncr) February 6, 2019
>>> tuple(None)
Traceback (most recent call last):
File «<stdin>», line 1, in <module>
TypeError: ‘NoneType’ object is not iterable
>>>— marcel corso professional tweeting (@marcelcorso) January 14, 2014
Some people even use the error as a joke!
I’m going to enumerate all the things I like about IE:
TypeError: ‘NoneType’ object is not iterable
— Daniel Marks (@madmax) December 30, 2010
Quick Video Fix
The YouTuber walks you through how to deal with the error:
In Python, the error message “TypeError: ‘NoneType’ object is not iterable” is caused by iterating or using loops on a None or null variable. Basically, in common practice, it is not allowed to loop through a non-array data. Take a look at this example code:
fruits = None
for fruit in fruits:
print(fruit)
In line 2, Python recognizes that we are trying to use a loop on the variable fruits. It will immediately throw the “TypeError: ‘NoneType’ object is not iterable” message because “fruits” is None or a null data. We cannot possibly loop through None or null; it is like counting how many books you have but actually, you do not have any declared.
Here is a basic example of how to properly iterate an array:
fruits = [“Apple”, “Banana”, “Mango”, “Grapes”]
for fruit in fruits:
print(fruit)
As you can see in line 1, we are declaring the variable fruits as an array of strings (fruits). This will give us the output without errors below because this time we are iterating an array and not a None.
Apple
Banana
Mango
Grapes
How to Fix the ‘TypeError: ‘NoneType’ object is not iterable’ Error
Sometimes, it is inevitable that variables or functions return None or null, and we accidentally force to loop through them causing this error to be thrown. However, there are multiple ways to fix this type of error by using the following methods:
1st Fix: Use the isinstance() Built-in Function
The isinstance() function will check if the object (first argument) is an instance or a subclass of classinfo class (second argument). We can use this built-in function to check if we should or we should not loop through a variable. Take a look at this code example:
fruits = None
if(isinstance(fruits, list)):
for fruit in fruits:
print(fruit)
else:
print(“Fruits variable is not an array”)
To avoid getting the error, you can follow these steps using the isinstance() built-in function:
- In line 1, if you declare the variable fruits as None and therefore makes Python understand it is surely not an array.
- In line 2, use an if statement using the isinstance() function as an argument to check if variable fruits is an array. This time the isinstance(fruits, list) function will return false making the argument to fail and will skip the for-loop avoiding the ‘TypeError: ‘NoneType’ object is not iterable’ and executes line 6 after the else statement giving the “Fruits variable is not an array” output.
Now we can proceed to the next code execution and fully avoid the ‘TypeError: ‘NoneType’ object is not iterable’ error message. The Python isinstance() built-in function is used in so many ways not just for this type of error handling.
2nd Fix: Exception Handling
In Python, we can handle errors and exceptions like the ‘TypeError’ error using the try except statement. Follow these steps for exception handling:
- Any errors and exceptions thrown inside the try statement will be caught and will skip to the except statement execution. Look at the example code below:
fruits = None
try:
for fruit in fruits:
print(fruit)
except:
print(“Fruits variable is not an array”)
- In this case, the fruits variable is None and code line number 3 will surely throw the ‘TypeError: ‘NoneType’ object is not iterable’ error; however, this will be caught and outputs “Fruits variable is not an array”.
We have avoided the error again using Python’s exception handling.
3rd Fix: The type() Built-in Function
Just like the isinstance() function in the first fix which determines if the passed argument is an instance of a data type and returns a boolean value, the type() function returns the data type of the passed argument. This is very useful while you figure out the type of variable used in runtime.
fruits = None
if type(fruits) is list:
for fruit in fruits:
print(fruit)
else:
print(“Fruits variable is not an array”)
This time, follow these steps if you prefer to use the type() built-in function:
- Check the datatype of the variable fruits and check if it is a list type using the “is” operator.
- In the code above, the if-statement is false and will not execute the for-loop and jumps to the “else” part of the condition avoiding the TypeError to be thrown by the system.
Look at the comparison of the type() and isintance function in Python.
Forum Feedback
To understand more about TypeError: NoneType object is not iterable, and the problems users have with it, we looked through several Python forums. In general, users are interested in TypeError: NoneType object is not iterable Python, TypeError: NoneType object is not iterable list, and TypeError: NoneType object is not iterable matplotlib.
They also wanted to know more about TypeError: NoneType object is not iterable tensorflow and TypeError: NoneType object is not iterable empire.
A Python novice started working on a code for a school project, and he couldn’t figure out why he was getting the TypeError: ‘NoneType’ object is not iterable.
- He asked the Python community, which was very helpful in solving the problem.
- They explained to him that the most likely scenario was that he had missed the return statement in his method.
- Since the method was returning “None,” and “None” was iterable, he was getting the error.
- However, the user added that it was a difficult mistake to spot for novices because of all the involved variables and warned that it might take you a while to figure it out.
A poster explains that NoneType is a type of None object or in other words, an object which has no value.
- The person specifies that lists have _iter_ method, which allows iteration. But since you can’t iterate over objects that are None, you get an error.
- He adds that objects should be checked for nullity with the following code – if obj is None: or if obj is not None: to avoid mistakes.
- The person also said that novices find it difficult to grasp the concept and often forget to set the return value.
Another computer expert said that making a typing mistake somewhere in the code might result in a NoneType object is not iterable. He advises that you check the spelling carefully to make sure that you’re doing everything as suggested by the Python Style Guide.
A person remarks that you might get a TypeError: ‘NoneType’ object is not iterable due to many reasons. However, one of the most common ones that new Python users do is that they iterate on numbers, while they should iterate on collections. To fix the issue, he says that you have to use one of these codes: for i in (number): or for i in ‘number’: and that you have to recheck all lines of code carefully and change it appropriately.
Another individual says that if you continue to get a NoneType error, you might have forgotten something as simple as quotation marks somewhere in a list you’re trying to return. So, he advises that you go over the code to find the mistake. The correct version should look similar to this – [‘word’, ‘word’, ‘word’], otherwise you’ll keep getting the same mistake because it can’t find the variable.
A computer user mentioned that he was trying to write a code to round-up grades, but he was getting a NoneType error in Python 3.x. He reached out the Python community for help, and they explained to him that his mistake was a simple one. The user had used “print” instead of “return,” and as a result, his function didn’t have anything to return.
Another person commented that TypeError: NoneType object is not iterable might be the result of a return statement indented incorrectly.
A forum poster shared that he was having some problems with matplotlib in Python 3.7.0.
- The program he wrote worked fine on another device, but when he tried it on his computer, he got the NoneType object is not iterable error.
- The user tried to switch from IDE to IDLE, reinstall matplotlib, and he even uninstalled Python and installed it again.
- After consulting with other forum members, he discovered that matplotlib has a bug in the 3.0.0 version, which was causing the TypeError.
- His options were to wait for the bug to be fixed or downgrade his version of matplotlib.
A forum member observed that he had checked his variables and that they were not None Type and that his program was running correctly on the first time. However, when he attempted to run it a second time, he kept getting NoneType object error. Other members of the Python community explained to him that he had problems with the logic in his code and that he hadn’t explicitly set a return.
Conclusion
To avoid getting the error ‘TypeError: ‘NoneType’ object is not iterable’, make sure that you have all the conditions in place that will return the data that you need. Do not use loops on a None or null variable as it will return this error. Basically, Python will iterate an array when you correctly declare the strings to be reported back.
For these suggested fixes, there are instances where the type() function is more applicable than the insintance() function in Python. The isintance() built-in function works with sub-classing while the type() built-in function will only return the type of object and return a comparison of the type of object of an object to be true if you use the exact same type object on both sides.
As you progress your programming experience, you will surely encounter hundreds, if not thousands, of this kind of error. You can predict that a given variable is not an array to be iterated or a function may return None so you could use the fixes given above. This error is common when you are just starting to write code. But, through time, dedication, and patience you will get used to catching and preventing this type of error as you build your apps and software.
Ryan is a computer enthusiast who has a knack for fixing difficult and technical software problems. Whether you’re having issues with Windows, Safari, Chrome or even an HP printer, Ryan helps out by figuring out easy solutions to common error codes.