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
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!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.