. Advertisement .
..3..
. Advertisement .
..4..
The “Typeerror: ‘Nonetype’ Object Is Not Iterable” is among the most popular errors you can encounter during operating on the Python project. To make you clear about it, we will show you the root causes, and how to solve this error simply.
When will the “Typeerror: ‘Nonetype’ Object Is Not Iterable” happen?
The “Typeerror: ‘Nonetype’ Object Is Not Iterable” will appear when you attempt to iterate over a “None” object.
For instance, here is the illustrated code from Python project. After you complete and run this code below, the error displays in the 6th line.
def myfunction():
a_list = [1,2,3]
a_list.append(4)
# return a_list
returned_list = myfunction()
for item in returned_list: “Typeerror: 'Nonetype' Object Is Not Iterable”
# do something with item
We will propose the main causes below.
- The function returning data is “None.”
- You forget to return a_list from my function().
How to fix this problem?
Solution 1: Check carefully, and iterate on the object whether the object is “None” or not
The first step is that you need to check carefully. Next, you can iterate on the object whether this object is “None” or not.
def myfunction():
a_list = [1,2,3]
a_list.append(4)
# return a_list
returned_list = myfunction()
if returned_list is None:
print("returned list is None")
else:
for item in returned_list:
# do something with item
Run this code and realize that this error is removed entirely.
Solution 2: Use the “For” loop in the “try-except” block
The following approach to this problem is using the “For” loop. Then, put it in the “try-except” block, run this code and check what happens.
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
Until the moment, this error has been solved completely.
Solution 3: Assign an empty list explicitly to the variable
The final solution is explicitly assigning the empty list in case it is “None”. Next, you run this code and see the result.
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
Great! This error is fixed successfully.
Conclusion
“Typeerror: ‘Nonetype’ Object Is Not Iterable” can be solved easily and rapidly if you read this post. You can drop us more feedback below if needed. Thank you!
Read more:
→ How To Fix TypeError: cannot unpack non-iterable NoneType object
Leave a comment